PHP Reference ยท Array Functions
PHP array_fill() and array_fill_keys()
Reference for PHP array_fill() and array_fill_keys(): create arrays filled with one value by index range or by a list of keys, plus object and array pitfalls.
array_fill() creates an array of a given size in which every element has the same value, starting at a chosen index. array_fill_keys() does the same for an explicit list of keys.
Both are useful for initializing counters, default settings and grids. Because the same value is copied into every slot, arrays are copied safely, but objects are shared: every element then points to the same object.
<?php print_r(array_fill(5, 3, "x")); // [5 => "x", 6 => "x", 7 => "x"] print_r(array_fill_keys(["a", "b"], 0)); // ["a" => 0, "b" => 0]
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_fill(int $start_index, int $count, mixed $value): array array_fill_keys(array $keys, mixed $value): array
| Name | Description |
|---|---|
$start_index |
The first index of the result. Subsequent indexes increase by one. |
$count |
How many elements to create. Must be zero or greater. |
$keys |
The keys of the result. Values that are not integers or strings are converted to strings. |
$value |
The value placed in every element. |
Return value: the new array.
Errors: array_fill() throws a ValueError if $count is negative or too large.
Usage notes
- Negative start index: since PHP 8.3 the following indexes continue by one from the start index (
-3, -2, -1); in earlier versions the second key was0. - Objects are shared, arrays are not. To get independent objects, build the array with a loop or
array_map(), or useclone. - A range of numbers is easier with
range(); a padded array witharray_pad(). - Count zero returns an empty array. Before PHP 8.0 it triggered a warning.
- Duplicate keys in
array_fill_keys()simply collapse into one element. - Preset defaults:
array_fill_keys($names, null)is a tidy way to list all expected fields before filling in some of them witharray_merge()or+.
Related
array_pad(),range(),array_combine(),str_repeat()- Lessons: Arrays, Array functions