PHP array_search() Function
The PHP array_search() function searches the array for a given value and returns the first corresponding key if successful.
Syntax
array_search(value, array, strict)
Parameters
value |
Required. Specify the searched value. If it is a string, the comparison is done in a case-sensitive manner. |
array |
Required. Specify the array. |
strict |
Optional. Specify true for strict comparison (===). |
Return Value
Returns the key for value if it is found in the array, false otherwise.
Note: If value is found in the array more than once, the first matching key is returned. To return the keys for all matching values, array_keys() with the optional search_value parameter can be used.
Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.
Exceptions
NA.
Example:
The example below shows the usage of array_search() function.
<?php $Arr = array(10, 20, 25, 25, 25, 30, 40); //searching value in the array echo "25 is found at index: ". array_search(25, $Arr)."\n"; echo "30 is found at index: ". array_search(30, $Arr)."\n"; ?>
The output of the above code will be:
25 is found at index: 2 30 is found at index: 5
Example:
Consider one more example where this function is used with an associative array.
<?php $Arr = array('r'=>'Red', 'b'=>'Blue', 'g'=>'Green'); //searching value in the array echo "Key of 'Blue': ". array_search('Blue', $Arr)."\n"; echo "Key of 'Green': ". array_search('Green', $Arr)."\n"; ?>
The output of the above code will be:
Key of 'Blue': b Key of 'Green': g
❮ PHP Array Reference