array_fill_keys

Creates an array using the given values as keys, all set to the same value.

Signature
array_fill_keys(array $keys, mixed $value): array
  • Added in PHP 5.2.0

Parameters

ParameterTypeDescription
$keysarrayAn array of values to use as keys. Values that are not valid keys are converted using PHP's normal key-casting rules.
$valuemixedThe value assigned to every key.

Return value

arrayAn array whose keys are the values of $keys, each holding $value.

array_fill_keys() takes a flat list of names and turns it into an associative array where every one of those names is a key holding the same starting value.

When to reach for it

Its main job is guaranteeing that a key exists. Initialise a counter map with array_fill_keys($categories, 0) and you can write $counts[$cat]++ without an isset() check or an undefined-key warning. Build a permission map with false defaults and flip on the ones that are granted. Create a template of expected form fields set to null, then array_merge() the submitted data over it so every field is present in the result whether the user filled it in or not.

It also pairs well with array_column(): pull the distinct values out of a result set and immediately use them as the skeleton of a grouped structure.

What trips people up

Keys go through PHP's normal casting. The string "7" becomes the integer 7, true becomes 1, false becomes 0, null becomes the empty string, and floats are truncated with a deprecation notice. Duplicate keys collapse, so the result can be shorter than the list you passed in.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Pre-seed a counter map so $counts[$key]++ never hits an undefined key
  • Build a permission matrix defaulting to false before switching on the granted ones
  • Create a template of expected form fields set to null and merge submitted data over it

Frequently asked questions

What is the difference between array_fill_keys and array_combine?

array_fill_keys gives every key the same single value, while array_combine pairs each key with the matching element of a second array. Use array_combine when the values differ per key.

Does array_fill_keys keep string keys like '10' as strings?

No. PHP converts numeric strings to integer keys, so '10' becomes the integer 10. Booleans, null and floats are converted too, following the usual array-key rules.

Is it safe to fill keys with an empty array for grouping?

Yes. Arrays are value types in PHP and copy on write, so each key gets its own array. Filling with an object is different — every key would share one instance.

More examples

Guaranteeing every field exists

Merging the submitted values over the null template gives a record with all four keys present. Missing fields are null instead of absent, so downstream code can read $record['phone'] without a warning.

Example · php
<?php
$expected  = array_fill_keys(['name', 'email', 'phone', 'notes'], null);
$submitted = ['name' => 'Ada', 'email' => '[email protected]'];

$record = array_merge($expected, $submitted);
print_r($record);
var_dump(array_key_exists('phone', $record));

Grouping rows into pre-made buckets

The distinct types become the buckets before the loop runs, so no isset() check is needed inside it. Arrays copy on write, so each bucket is genuinely independent.

Example · php
<?php
$rows = [['t' => 'bug', 'id' => 1], ['t' => 'feat', 'id' => 2], ['t' => 'bug', 'id' => 3]];

$buckets = array_fill_keys(array_unique(array_column($rows, 't')), []);
foreach ($rows as $r) { $buckets[$r['t']][] = $r['id']; }

print_r($buckets);

Keys are cast, and duplicates collapse

'5' and 5 land on the same integer key, true becomes 1 and null becomes the empty string, so five inputs produce four entries. No warning is raised — count the result if key uniqueness matters.

Example · php
<?php
$out = array_fill_keys(['5', 5, true, null, 'five'], 'v');

var_dump($out);
echo "5 keys in -> ", count($out), " keys out\n";

Discussion

  • Be the first to comment on this lesson.