PHP array_search() Function
PHP array_search() Function
The array_search() function in PHP searches the array for the specified value. This function returns the first corresponding key if the value is found.
Syntax
array_search ( mixed $needle , array $haystack [, bool $strict ])
Parameter
needle(required)- This parameter represents the value to search.
haystack(required)- This parameter signifies the input array.
strict(optional)- This parameter signifies the strictness of the search. It takes only Boolean values which are as follows:
- If it is set to Boolean TRUE, the function checks only for identical elements.
- If set to Boolean FALSE(default), strictness is not maintained.
Return
This function returns the first corresponding key if the needle value is found else it returns false.
Example 1
'blue', 1 => 'red', 2 => 'green', '' => 'red'); //passing the searched value $search_value='red'; //returns the first key if the value is found $key = array_search($search_value, $array); // $key = 2; //printing the key echo("The ".$search_value." is found at key position ".$key);
Output
The red is found at key position 1
Example 2
Output
The value 90 is found at key position 1Example 3
Output
When strictness is set to true... The value 90 is found at key position When strictness is set to false... The value 90 is found at key position 1Example 4
Output
The value 90 is found at key position