PHP Reference ยท Array Functions
PHP array_keys() function
Reference for PHP array_keys(): list the keys of an array, or only the keys whose value matches, with loose and strict comparison and common patterns.
The array_keys() function returns the keys of an array as a new list. Called with a second argument, it returns only the keys whose values equal that argument, which makes it a way to find every position of a value, not just the first.
The result is always a re-indexed list: its own keys are 0, 1, 2 and so on, and its values are the original keys.
print_r(array_keys(["a" => 1, "b" => 2])); // ["a", "b"] print_r(array_keys([5, 6, 5], 5)); // [0, 2]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_keys(array $array): array array_keys(array $array, mixed $filter_value, bool $strict = false): array
| Name | Description |
|---|---|
$array |
The array to read. |
$filter_value |
Optional. Only keys whose value matches this are returned. |
$strict |
Optional. If true, values are compared with === (type must match). Default false uses ==. |
Return value: a list of keys, in the original order. An empty array if nothing matches.
Errors / Exceptions: a TypeError if the first argument is not an array.
Usage notes
$filter_valuecan benull, which is meaningful:array_keys($a, null)finds keys whose value is loosely equal tonull(so also0,false,""and[]). Use$strict = trueto match only realnull.- Without the filter argument, the loose/strict flag is not available; you must pass a filter value to use it.
- Loose comparison can match more than you expect: in the example above, searching for
0also returns the keys of"0",falseandnull. Prefer strict mode when types matter. - Find only the first match with
array_search(). Test for existence within_array(). - Keys of the result are 0..n-1. Integer-like string keys come back as integers.
- For a quick check of one key,
array_key_exists()is cheaper than searching the key list. array_keys()copies the keys, so on huge arrays iterate withforeach ($a as $k => $v)instead when you do not need a list.