How to Use array_keys in PHP: Syntax and Examples
In PHP,
array_keys returns all the keys from an array. You can optionally pass a value to get only keys matching that value. It helps you find keys quickly without looping manually.Syntax
The array_keys function has this syntax:
array_keys(array $array, mixed $search_value = null, bool $strict = false): array
Parameters:
$array: The input array to get keys from.$search_value(optional): If given, only keys with this value are returned.$strict(optional): If true, uses strict type comparison when searching.
The function returns an array of keys.
php
array_keys(array $array, mixed $search_value = null, bool $strict = false): array
Example
This example shows how to get all keys from an array and how to get keys for a specific value.
php
<?php
$fruits = [
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry',
'd' => 'banana'
];
// Get all keys
$allKeys = array_keys($fruits);
print_r($allKeys);
// Get keys where value is 'banana'
$bananaKeys = array_keys($fruits, 'banana');
print_r($bananaKeys);
?>Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
Array
(
[0] => b
[1] => d
)
Common Pitfalls
One common mistake is forgetting that array_keys returns an array of keys, not a single key. Also, when searching for a value, if you don't set $strict to true, PHP uses loose comparison which can cause unexpected matches.
Example of loose vs strict search:
php
<?php
$array = [
0 => '0',
1 => 0,
2 => false
];
// Loose search (default)
$keysLoose = array_keys($array, 0);
print_r($keysLoose);
// Strict search
$keysStrict = array_keys($array, 0, true);
print_r($keysStrict);
?>Output
Array
(
[0] => 0
[1] => 1
[2] => 2
)
Array
(
[0] => 1
)
Quick Reference
| Parameter | Description |
|---|---|
| $array | The input array to extract keys from. |
| $search_value (optional) | Value to filter keys by matching values. |
| $strict (optional) | Use strict comparison (===) when searching values. |
Key Takeaways
Use array_keys to get all keys or keys matching a specific value from an array.
Passing a value to array_keys filters keys to those with that value.
Set the strict parameter to true to avoid loose comparison surprises.
array_keys always returns an array of keys, even if only one key matches.
It's a quick way to find keys without writing loops.