How to use the array_search function in PHP?

The function array_search is used to search for a specific value in an array and return the corresponding key. Here is how it is used:

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Instructions for parameters:

  1. $needle: The value to search for.
  2. $haystack: Array to be searched.
  3. $strict (optional): Specifies whether to use strict mode for comparison, default is false. If set to true, data types will be compared during the search.

Return value:

  1. Return the key name corresponding to the specified value if found.
  2. If the specified value is not found, return false.

I’m sorry, I don’t understand the question.

$fruits = array("apple", "banana", "orange", "grape");

$key = array_search("banana", $fruits);
echo $key;  // 输出 1

$key = array_search("apple", $fruits);
echo $key;  // 输出 0

$key = array_search("watermelon", $fruits);
echo $key;  // 输出 false

In the example above, we used the array_search function to search for certain values in the array $fruits. If the specified value is found, it returns the corresponding key name; if not found, it returns false.

bannerAds