How to Use the PHP array_keys() Function



In this article, you will learn how to use the PHP array_keys() function.

PHP array_keys() Function

The array_keys() function in PHP is used to get all the keys or a subset of the keys of an array. The function takes an array as an argument and returns an array containing all the keys of the input array.

array_keys(array $array [, mixed $search_value = null [, bool $strict = false ]] ) : array
  • $array: The required parameter and it specifies the input array from which you want to get the keys.
  • $search_value (optional): This parameter specifies the value to search for. If specified, array_keys() will only return the keys that have this value in the input array.
  • $strict (optional): This parameter specifies whether type comparisons should be strict or not. If strict is set to TRUE, then array_keys() will only return the keys that have values that are equal (in value and type) to the search_value. If strict is set to FALSE or not specified, then type conversions will be performed if necessary to make the comparison.
  $fruits = array("apple"=>"red", "banana"=>"yellow", "cherry"=>"red");
  $keys = array_keys($fruits, "red");
Array ( [0] => apple [2] => cherry )

In the above example, the array_keys() function is used to get only the keys of the $fruits array that have the value “red”.