Home >Backend Development >PHP Tutorial >PHP array search function in_array(), array_search(), array_key_exists() usage examples_PHP tutorial
There are many ways to find whether a specified value exists in an array in PHP. I remember that a long time ago I foolishly used a foreach loop to find it. Now I will mainly share how to use PHP’s three built-in array functions to find a specified value. Whether the value exists in the array, the three arrays are in_array(), array_search(), array_key_exists().
First of all, let’s introduce their respective definitions and functions
in_array(value,array,type)
The function of this function is to search for the specified value in the array. type is an optional parameter. If this parameter is set to true, it will check whether the type of the searched data and the value of the array are the same, that is, they are equal to each other.
Example:
Output:
Match found
array_key_exists(key,array)
This function is to determine whether the specified key exists in an array. If the key exists, it returns true, otherwise it returns false.
Example:
Output:
Key exists!
array_search(value,array,strict)
The array_search() function is the same as in_array(), searching for a key value in the array. If the value is found, the key name matching the element is returned. If not found, returns false. Note that prior to PHP 4.2.0, functions returned null instead of false on failure. Similarly, 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.
Example:
Output:
ad
After actual performance comparison, when the amount of data is not large, such as less than 1000, any search method can be used, and it will not become a performance bottleneck. But when the amount of data is relatively large, it is more appropriate to use array_key_exists. According to tests, array_key_exist is more than ten or even dozens of times more efficient than in_array.