Home  >  Article  >  Backend Development  >  PHP array operation-delete specified array elements_PHP tutorial

PHP array operation-delete specified array elements_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 16:59:38959browse

This article condenses the usage of various functions in PHP to remove array elements according to specified element values. Friends in need can refer to it.

Remove array elements by specified element value

The code is as follows
 代码如下 复制代码

$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r($a);
unset($a[array_search("Cat",$a)]);
//array_search("Cat",$a)按元素值返回键名。去除后保持索引
print_r($a);
?>

Copy code

$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");

 代码如下 复制代码

去除前:
Array
(
    [a] => Dog
    [b] => Cat
    [c] => Horse
)

去除后:

Array
(
    [a] => Dog
    [c] => Horse
)

print_r($a);

unset($a[array_search("Cat",$a)]);
//array_search("Cat",$a) returns the key name by element value. Keep index after removal
print_r($a);

?>

The following will talk about the usage of array_search

Show results

Array
The code is as follows
Copy code


Before removal:
Array
( [a] => Dog

[b] => Cat

[c] => Horse
 代码如下 复制代码
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
echo array_search("Dog",$a);
?>输出:
)

After removal:
( [a] => Dog

[c] => Horse

) array_search() definition and usage The array_search() function, like in_array(), searches for a key value in an array. If the value is found, the key of the matching element is returned. If not found, returns false. Prior to PHP 4.2.0, functions returned null instead of false on failure. If the third parameter strict is specified as true, the key name of the corresponding element will only be returned if the data type and value are consistent.
Grammar array_search(value,array,strict) parameter description value required. Specifies the value to search for in the array.
array required. The array to be searched.
strict optional. Possible values: true false - default If the value is set to true, the type of the given value is also checked in the array. (see example 2) Example 1
The code is as follows Copy code
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); echo array_search("Dog",$a); ?>Output: a http://www.bkjia.com/PHPjc/631312.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631312.htmlTechArticleThis article condenses the usage of various functions in PHP to remove array elements by specified element values, if necessary Friends can refer to it. Remove array elements by specified element value. The code is as follows...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn