PHP array_fill_keys() Function

What is PHP array_fill_keys() Function?

array_fill_keys() function creates an array filling keys from values of an array and filling values from a provided value or values of another array.

Syntax:

array_fill_keys(keys, value)

Parameters:

The Function has 2 parameters; both are required-

keys (Required): It is an array whose values the function uses as keys in the new array.

values (Required): It is a value (string, integer etc) or a list of values (array) that the function uses as values in the new array.

Return Values:

The function returns an array filled with provided array and value pair or array or array pair.

Examples:

Example 1:

<pre>
<?php
$keys = ['Physics', 'Chemistry', 'Math', 'Language'];
$value = 100;
$last_array = array_fill_keys($keys, $value);
print_r($last_array);
?>
</pre>

Output:

Array
(
    [Physics] => 100
    [Chemistry] => 100
    [Math] => 100
    [Language] => 100
)

Example 2:

<pre>
<?php
$keys = ['Physics', 'Chemistry', 'Language'];
$value = ['1st' => 100, '2nd' => 'N/A'];
$last_array = array_fill_keys($keys, $value);
print_r($last_array);
?>
</pre>

Output:

Array(
    [Physics] => Array
        (
            [1st] => 100
            [2nd] => N/A
        )
     [Chemistry] => Array
        (
            [1st] => 100
            [2nd] => N/A
        )
     [Language] => Array
        (
            [1st] => 100
            [2nd] => N/A
        ) 
)

Practical Usages of array_fill_keys() Function:

This function is very useful when you want to quickly create an array filling with pre-defined keys and values.

Notes on array_fill_keys() Function:

  • Illegal values for key will be converted to string.

PHP Version Support:

PHP 5 >= 5.2.0, PHP 7, PHP 8

Summary: PHP array_fill_keys() Function

If you want to create an array filling with pre-defined values for its keys and values, use array_fill_keys() function which is a built-in PHP array function.

Reference:

https://www.php.net/manual/en/function.array-fill-keys.php