In PHP development, arrays are one of the most commonly used data structures. During development, when debugging arrays, sometimes we only care about the keys (indexes) rather than the corresponding values. Printing only the array keys helps to better understand the array structure and facilitates further operations and analysis.
array_keys(array $array, mixed $search_value = null, bool $strict = false): array
$array: Required. Specifies the array to search keys from.
$search_value: Optional. Specifies the value to search for. If provided, only keys matching this value are returned.
$strict: Optional. Whether to use strict comparison (type and value must both match). Default is false.
The following example demonstrates how to get all the keys of an array:
$array = array("first" => 1, "second" => 2, "third" => 3, "fourth" => 4);
$arrKeys = array_keys($array);
print_r($arrKeys);
Output:
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
If you want to find the keys for the value 2 only, you can do the following:
$array = array("first" => 1, "second" => 2, "third" => 3, "fourth" => 4);
$arrKeys = array_keys($array, 2);
print_r($arrKeys);
Output:
Array
(
[0] => second
)
When strict comparison is enabled, both type and value are considered:
$array = array("first" => 1, "second" => 2, "third" => "2", "fourth" => 4);
$arrKeys = array_keys($array, 2, true);
print_r($arrKeys);
Output:
Array
(
[0] => second
)