PHP 8 reference · Array Functions
PHP array_fill_keys() Function
Create an array from a list of keys, giving every key the same value. Useful for defaults and counters.
PHP 8 Since 5.2
Syntax
array_fill_keys(array $keys, mixed $value): array
Parameters
| Parameter | Description |
|---|---|
keys |
The keys to use. |
value |
The value for every key. |
Return value
The new array.
Examples
<?php
print_r(array_fill_keys(["tea", "cake", "milk"], 0));
Output
Array
(
[tea] => 0
[cake] => 0
[milk] => 0
)<?php
$fields = ["name", "email", "phone"];
$form = array_merge(array_fill_keys($fields, ""), ["name" => "Ada"]);
print_r($form);
Output
Array
(
[name] => Ada
[email] =>
[phone] =>
)Version history
| Version | Change |
|---|---|
| PHP 5.2 | Added |
In other languages
dict.fromkeys()· Python
Related
array_fill()· Create an array filled with the same value, given a start index and a count.array_combine()· Create an array by using one array for keys and another for values. Both arrays must have the same number of elements.- PHP Arrays · tutorial
- PHP Array Functions · tutorial