PHP array_keys() Function
The PHP array_keys() function returns an array containing all the keys or a subset of the keys of an array. In first version, it returns all keys of the specified array. In second version, it returns all those keys of the specified array with value equal to search_value.
Syntax
//first version array_keys(array) //second version array_keys(array, search_value, strict)
Parameters
array |
Required. Specify the input array. |
search_value |
Optional. If specified, then keys containing this value are returned. |
strict |
optional. Specify true for strict comparison (===). |
Return Value
Returns an array containing all the keys or a subset of the keys of an array.
Exceptions
NA.
Example: using with indexed array
The example below shows the usage of array_keys() function when used with indexed array.
<?php $Arr = array(10, 20, 30, 20, 40, 20); //array containing all keys of Arr $key_Arr1 = array_keys($Arr); //array containing keys of Arr with value 20 $key_Arr2 = array_keys($Arr, 20); print_r($key_Arr1); echo "\n"; print_r($key_Arr2); ?>
The output of the above code will be:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) Array ( [0] => 1 [1] => 3 [2] => 5 )
Example: using with associative array
Consider one more example where array_keys() function is used with an associative array.
<?php $Arr = array(101=>"Red", 102=>"Blue", 103=>"Green", 104=>"White", 105=>"Black", 106=>"Green"); //array containing all keys of Arr $key_Arr1 = array_keys($Arr); //array containing keys of Arr with value "Green" $key_Arr2 = array_keys($Arr, "Green"); print_r($key_Arr1); echo "\n"; print_r($key_Arr2); ?>
The output of the above code will be:
Array ( [0] => 101 [1] => 102 [2] => 103 [3] => 104 [4] => 105 [5] => 106 ) Array ( [0] => 103 [1] => 106 )
❮ PHP Array Reference