Lesson 47 of 100
Arrays15 min5 checksPHP 8.5

Work with Array Keys and Values

Learn to separate keys from values with array_keys() and array_values(), filter keys by value, and choose strict or loose matching.

01 · THE IDEAREAD → TRY → LEARN

Keys and values are two views of one array

Every PHP array is an ordered map. Each entry has a key, which is an integer or a string, and a value, which can be anything. Sometimes you only care about one side. You might want the labels in a report, or just the numbers to total. PHP gives you array_keys() and array_values() to pull out each side.

Both functions return a new list. The original array is not changed. The results follow the order of the source array, so the first entry's key or value comes first.

Extracting each side

The signature of the basic form is array_keys(array $array): array. It returns every key, numeric and string, as a list of values. array_values() returns the values and renumbers them from zero.

Example
<?php
$stock = ['apple' => 4, 'pear' => 0, 'plum' => 4];
echo json_encode(array_keys($stock)), "\n";
echo json_encode(array_values($stock)), "\n";
Output
["apple","pear","plum"]
[4,0,4]

The keys come back as ["apple","pear","plum"] and the values as [4,0,4]. Notice that the duplicate value 4 appears twice. Values are not required to be unique. Keys are.

Finding the keys for a value

The second form is array_keys(array $array, mixed $filter_value, bool $strict = false): array. When you pass a filter value, only keys whose entries match that value are returned. This works like a reverse lookup: you know the value and want to know where it lives.

The third parameter controls how matching works. By default the comparison is loose, so 4 matches the string '4'. With $strict set to true, PHP uses ===, so both the value and its type must match.

Example
<?php
$stock = ['apple' => 4, 'pear' => 0, 'plum' => 4, 'fig' => '4'];
echo json_encode(array_keys($stock, 4)), "\n";
echo json_encode(array_keys($stock, 4, true)), "\n";
Output
["apple","plum","fig"]
["apple","plum"]

The loose search returns apple, plum and fig. The strict search leaves out fig, because its value is a string. If nothing matches, you get an empty array, not false. That makes the result safe to loop over or count without a special check.

Keys are not always a tidy sequence

Removing an element does not renumber the others. After unset(), the remaining keys keep their original numbers, and the array can have gaps. At that point array_keys() and array_values() give very different results.

Example
<?php
$queue = ['a', 'b', 'c', 'd'];
unset($queue[1]);
echo json_encode($queue), "\n";
echo json_encode(array_keys($queue)), "\n";
echo json_encode(array_values($queue)), "\n";
Output
{"0":"a","2":"c","3":"d"}
[0,2,3]
["a","c","d"]

The array now has keys 0, 2 and 3, so json_encode() writes it as an object. array_keys() shows the gaps, while array_values() gives a compact list with fresh keys 0, 1, 2. Use array_values() when you need a clean list. Use array_keys() when the original positions or labels matter.

Common pitfalls

  • Loose matching surprises. Without $strict, values such as 0, null, false and '' can compare as equal under loose rules. When type matters, pass true.
  • Assuming keys are strings. Keys of a list are integers, so array_keys(['x', 'y']) returns [0, 1].
  • Expecting a single key. array_keys() with a filter returns all matching keys, in array order. Take the first element yourself if you only need one.
  • Forgetting the original is unchanged. Assign the result to a variable if you need it later.

Exercise contract

Write keysWithValue(array $items, mixed $needle): array. It must return a list of every key in $items whose value is strictly identical to $needle, in the original order. If there are no matches, return an empty array. The tests check the returned values, not printed output. They include a case where 1 and '1' must be told apart, and a case where null must not match 0.

Recap

array_keys() returns the keys, optionally limited to those whose value matches a filter. array_values() returns just the values, renumbered. Matching is loose unless you pass true, and a search with no match returns an empty array. Reach for strict matching whenever the type of the value is part of what you are asking.

Before you start

Functions · Arrays · Types

You’ll practice
  • Separate keys from values and preserve expected ordering
  • Implement and test a deterministic PHP 8.4 function
Your task

Make keysWithValue() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.