Home > Backend Development > PHP Tutorial > php array_search function usage

php array_search function usage

WBOY
Release: 2016-07-29 08:42:18
Original
1684 people have browsed it

Definition and usage

array_search() function is the same as in_array(), searching 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.

Syntax

array_search(value,array,strict)
Copy after login
Parameters 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 will also be checked in the array. (See Example 2)


Example #1 array_search() Example

Copy code The code is as follows:


$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>


Warning
This function may return the Boolean value FALSE, but it may also return a non-Boolean value equivalent to FALSE, such as 0 or"". See the Boolean types chapter for more information. The === operator should be used to test the return value of this function.
Example 1

Copy the code The code is as follows:


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


Output: a
Example 2

Copy the code The code is as follows:


$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
? >


Output:
b

The above introduces the use of the php array_search function, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template