Arrays7 min readExamples run on PHP 8.5.10

array_fill_keys()

Learn how array_fill_keys() turns a list of values into array keys that all share one value, with PHP 8.4 examples, edge cases and common mistakes.

Signature

array_fill_keys(array $keys, mixed $value): array
Available since PHP 5.2.07.48.08.18.28.38.48.5All versions →

Purpose

array_fill_keys() builds a new array from a list of keys. You pass in an array whose values should become the keys of the result, plus one value. Every key in the result is assigned that same value.

Typical uses are creating a counter table where every category starts at 0, building a default record where every field is null, and making a lookup set where each key maps to true.

Signature

Parameters and defaults

  • $keys: an array whose values are used as keys in the result. The keys of this input array are ignored, and only its values matter. Values that are not valid array keys are converted to strings.
  • $value: the value stored under every key. It can be any type, including null, an array or an object. Neither parameter has a default, so both are required.

Return value and failure cases

The function returns a new array. An empty $keys array gives an empty array back. The input array is not modified.

Passing something that is not an array as $keys raises a TypeError, because the parameter is typed. Do not pass nested arrays or objects as key values. They are not meaningful keys, and the conversion will not do what you want.

Example 1: basic use, duplicates and numeric strings

Keys behave like normal PHP array keys. A repeated key appears only once. A string that looks like a decimal integer, such as "7", becomes the integer key 7. A string such as "07" stays a string, because it is not the canonical form of an integer.

Example
<?php
$keys = ['a', 'b', 'a', '7', '07'];
$result = array_fill_keys($keys, 0);
echo json_encode($result), PHP_EOL;
Output
{"a":0,"b":0,"7":0,"07":0}

The result has four entries, since the second 'a' overwrites the first. The "7" and "07" keys stay distinct.

Example 2: a counter table

A common job is counting occurrences while making sure that categories with no matches still appear in the result. Start every known category at zero, then increment.

Example
<?php
$counts = array_fill_keys(['red', 'green', 'blue'], 0);
$words = ['red', 'blue', 'red'];

foreach ($words as $word) {
    $counts[$word]++;
}

echo json_encode($counts), PHP_EOL;
Output
{"red":2,"green":0,"blue":1}

Because green was pre-filled, it appears with a count of 0. Without the pre-fill, you would have to check each key before incrementing it.

Example 3: array values are copied

If $value is an array, each key receives its own copy under PHP's normal value semantics. Changing one entry does not change the others.

Example
<?php
$groups = array_fill_keys(['x', 'y'], []);
$groups['x'][] = 1;
echo json_encode($groups), PHP_EOL;
Output
{"x":[1],"y":[]}

This makes the function convenient for creating empty buckets to group items into later.

Edge cases

  • Order is preserved. Keys appear in the order of the input values. If a key repeats, the first position is kept and the value is simply overwritten with the same value.
  • Input keys are ignored. array_fill_keys(['p' => 'a', 'q' => 'b'], 1) produces keys a and b, not p and q.
  • Objects share a handle. If $value is an object, every key refers to the same object instance. Mutating the object through one key is visible through all of them. Arrays do not behave this way, as Example 3 shows.
  • Empty input. An empty key list produces an empty array, regardless of $value.
  • Key conversion. Integers stay integers and decimal-integer strings become integer keys. For unusual values such as floats, booleans or null, the manual says only that illegal key values are converted to string. Normalise such input yourself if the exact key matters.

Common mistakes

  1. Expecting the input keys to be preserved. The function uses the values of $keys. If you want to pair two arrays that each have their own contents, use array_combine() instead.
  2. Confusing it with array_fill(). array_fill() creates consecutive numeric indexes from a start index and a count. array_fill_keys() takes explicit keys of your choosing.
  3. Assuming each key gets a fresh object. Passing new stdClass as $value creates one object that every key shares. If you need separate objects, build the array in a loop.
  4. Forgetting duplicate collapse. A list with repeated entries produces fewer elements than the input has. Do not rely on count($result) === count($keys) when duplicates are possible.
  5. Passing nested data as keys. Arrays and objects are not valid keys. Flatten or map the data to strings first.
  • array_fill(): fill an array with a value at consecutive numeric indexes.
  • array_combine(): use one array for keys and another for values.
  • array_flip(): swap keys and values of an existing array.
  • array_keys(): extract the keys of an array, the opposite direction.
  • array_replace(): overlay supplied values on top of a defaults array built with array_fill_keys().

Recap

array_fill_keys($keys, $value) returns a new array whose keys are the values of $keys, all holding the same $value. Duplicates collapse, decimal-integer strings become integer keys, array values are copied per key, and object values are shared. Use it for counters, default records and lookup sets, and reach for array_combine() when each key needs its own value.

Tested examples

Basic use with duplicates and numeric strings
<?php
$keys = ['a', 'b', 'a', '7', '07'];
$result = array_fill_keys($keys, 0);
echo json_encode($result), PHP_EOL;
Output
{"a":0,"b":0,"7":0,"07":0}
A counter table pre-filled with zeros
<?php
$counts = array_fill_keys(['red', 'green', 'blue'], 0);
$words = ['red', 'blue', 'red'];

foreach ($words as $word) {
    $counts[$word]++;
}

echo json_encode($counts), PHP_EOL;
Output
{"red":2,"green":0,"blue":1}
Array values are copied for each key
<?php
$groups = array_fill_keys(['x', 'y'], []);
$groups['x'][] = 1;
echo json_encode($groups), PHP_EOL;
Output
{"x":[1],"y":[]}