Definition and usage
The array_search () function is the same as the in_array () function. You can find a key value in the array. If this value is found, the key name of the matching element is returned. If not found, false is returned.
Before PHP 4.2.0, the function returns null instead of false in case of failure.
If the third parameter strict is set to true, the key name of the corresponding element is returned only when the data type and value are consistent.
Syntax
array_search(value,array,strict)
| Parameters |
Description |
| Value |
Required. Specifies the value to be searched in the array. |
| Array |
Required. The searched array. |
| Strict |
Optional. Possible values:
If the value is set to true, the type of the given value is also checked in the array. (See example 2) |
Example #1 array_search () Example
Copy codeThe Code is as follows:
<? Php
$ 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 a Boolean value of FALSE, but may also return a non-Boolean value equivalent to FALSE, such as 0 or "". For more information, see the Boolean section. The = operator should be used to test the return value of this function.
Example 1
Copy codeThe Code is as follows:
<? Php
$ A = array ("a" => "Dog", "B" => "Cat", "c" => "Horse ");
Echo array_search ("Dog", $ );
?>
Output:
Example 2
Copy codeThe Code is as follows:
<? Php
$ A = array ("a" => "5", "B" => 5, "c" => "5 ");
Echo array_search (5, $ a, true );
?>
Output:
B