The array_keys()
function in PHP returns all the keys (or indices) of an array. It can be used to get all the keys of an associative or indexed array. You can also specify a value to search for, and it will return only the keys that correspond to that value.
Syntax:
array_keys(array $array, mixed $value = null, bool $strict = false): array
- $array: The input array.
- $value (optional): If specified, only the keys for this value will be returned.
- $strict (optional): If set to
true
, the function will use strict comparison (i.e., checks both value and type).
Examples:
- Basic Example (Get all keys):
$array = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$keys = array_keys($array);
print_r($keys);
Output:
Array
(
[0] => a
[1] => b
[2] => c
)
- Search for Keys by Value (Find keys for a specific value):
$array = ['a' => 'apple', 'b' => 'banana', 'c' => 'apple'];
$keys = array_keys($array, 'apple');
print_r($keys);
Output:
Array
(
[0] => a
[1] => c
)
- Strict Comparison (Compare both value and type):
$array = [1 => 100, 2 => '100', 3 => 200];
$keys = array_keys($array, 100, true); // strict comparison (value and type)
print_r($keys);
Output:
Array
(
[0] => 1
)
- Using with Indexed Array:
$array = [10, 20, 30, 40];
$keys = array_keys($array);
print_r($keys);
Output:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
Summary:
array_keys()
is useful for getting the keys of an array.
- You can filter the keys based on a value.
- Using strict comparison ensures both the value and the type match.