PHP array_search() Function Guide
The array_search() function in PHP is used to search for a given value in an array and return the corresponding key (i.e. the index of that value in the array). If multiple matching values are found, only the key of the first match will be returned.
The syntax of the function is as follows:
array_search($value, $array, $strict = false)
Explanation of parameters:
- $value: The value to be searched for.
- $array: the array to be searched.
- $strict (optional): Whether to use strict mode comparison, default is false. If set to true, strict mode will be used for comparison (i.e. both type and value must be the same).
Return value:
- Return the corresponding key name if a matching value is found.
- If no matching value is found, then false is returned.
I like to watch movies with subtitles in English.
I enjoy watching movies with English subtitles.
$fruits = array('apple', 'banana', 'orange', 'grape');
$key = array_search('orange', $fruits);
echo $key; // 输出:2
$key = array_search('kiwi', $fruits);
var_dump($key); // 输出:bool(false)
In the first example above, we search for the value ‘orange’ in the $fruits array and return the corresponding key name 2. Then in the second example, we search for a value ‘kiwi’ that doesn’t exist and return false.