In this tutorial, we are going to learn how to work with PHP array search functions and methods like search array by PHP array_search() built-in function and PHP loops.
PHP array search content
PHP array_search() function
PHP array_search() function, searches the array for a given value. It returns the first corresponding key if the search was successful.
array_search(search_term, array, strict);
search_term | Required | The searched value |
array | Required | The array |
strict | Optional | If it is “true” then the function will search for identical elements in the array. It will perform a strict type (objects must be in the same instance) comparison of the search_term in the arra. |
Returned Value | Returns the key for search_term if it is found in the array, if the search action isn’t successful then returns “false”. |
If there is more than one element that matches the search term, the first matching key is returned.
$cars = array(
'fer' => 'Ferrari',
'ben' => 'Benz',
'bmw' => 'BMW',
'vol' => 'Volvo'
);
var_dump(array_search('Benz', $cars));
Output
ben
array_keys() function to search array in PHP
In PHP, the array_search() function returns the first key of the search_term if it is found. To return the keys for all matching values, use the array_keys() function with the optional search_term parameter instead.
array_keys(array, search_term);
$cars = array(
'fer' => 'Ferrari',
'ben' => 'Benz',
'bmw' => 'BMW',
'ben2' => 'Benz'
);
var_dump(array_keys($cars, 'Benz'));
Output
array (size=2)
0 => string 'ben' (length=3)
1 => string 'ben2' (length=4)
array_key_exists() function
array_key_exists() is a built-in PHP function to check if the given key exists in the array or not. This function returns “true” if the given key
is set in the array.
$cars = array(
'fer' => 'Ferrari',
'ben' => 'Benz',
'bmw' => 'BMW',
'vol' => 'Volvo'
);
var_dump(array_key_exists('ben', $cars));
Output
true
in_array() function
PHP in_array() function checks if a value exists in an array or not.
$cars = array(
'fer' => 'Ferrari',
'ben' => 'Benz',
'bmw' => 'BMW',
'vol' => 'Volvo'
);
var_dump(in_array('Benz', $cars));
Output
true