PHP array_fill_keys() Function
Quick summary: The PHP array_fill_keys() function fills an array with values, using keys from another array.
PHP array_fill_keys() Syntax
array_fill_keys(array $keys, mixed $value): array
PHP
PHP array_fill_keys() Basic examples
$keys = ['a','b','c'];
print_r(array_fill_keys($keys, 0));
PHP
Output:
Array ( [a] => 0 [b] => 0 [c] => 0 )
Creates an array using given keys and same value.
PHP array_fill_keys() Real-world usage
$fields = ['name','email','phone'];
$defaults = array_fill_keys($fields, null);
print_r($defaults);
PHP
Output:
Array ( [name] => [email] => [phone] => )
Initialize default values for form fields.
PHP array_fill_keys() Edge cases
$keys = ['a', 1, true];
print_r(array_fill_keys($keys, 'x'));
PHP
Output:
Array with normalized keys
Keys are cast to string or integer internally.
PHP array_fill_keys() Common mistakes
Passing non-array keys
First argument must be an array of keys.
Incorrect
array_fill_keys('abc', 1);
Correct
array_fill_keys(['a','b','c'], 1);
Provide an array of keys.
PHP array_fill_keys() Frequently Asked Questions
What does array_fill_keys() do?
Creates an array using keys with the same value.
Syntax?
array_fill_keys(keys, value).
Use case?
Initialize associative arrays.
Common mistake?
Duplicate keys.
Return type?
Array.
Handles objects?
Yes.
Performance?
Fast.
Safe?
Yes.
Alternative?
Manual loop.
Handles empty keys?
Returns empty array.
Best practice?
Ensure unique keys.
Used in configs?
Yes.