array_fill_keys() Function Use in PHP

In PHP, the array_fill_keys() function is used to create a new array with the specified keys and values. This function is similar to array_fill() but allows you to specify the keys instead of just the index.

Version Support: array_fill_keys() in PHP 8.5, array_fill_keys() in PHP 8.4, array_fill_keys() in PHP 8.3, array_fill_keys() in PHP 8.2, array_fill_keys() in PHP 8.1, array_fill_keys() in PHP 7.1, array_fill_keys() in PHP 7.2, array_fill_keys() in PHP 7.3, array_fill_keys() in PHP 7.4

The general syntax for array_fill_keys() is:

array_fill_keys($keys, $value)

Here:

$keys is an array of keys to be used in the new array.
$value is the value to be assigned to each key.

Here is an example:

<?php

$keys = array( name , age , city );
$values = array( John Doe , 30, New York );
$result = array_fill_keys($keys, $values[0]);
print_r($result);

?>

Output:

Array
(
   [name] => John Doe
   [age] => John Doe
   [city] => John Doe
)

In this example, we ve specified the keys as name, age, and city, and the value as John Doe . The resulting array has the specified keys and the value John Doe .

Note that if the number of keys and values is not the same, the function will assign the value to the remaining keys. If the number of keys is greater than the number of values, the remaining keys will be assigned NULL as their value.

You can also use this function to create an array with default values for certain keys. 

For example:

<?php

$keys = array( name , age , city );
$result = array_fill_keys($keys, Unknown );
print_r($result);

?>

Output:

Array
(
   [name] => Unknown
   [age] => Unknown
   [city] => Unknown
)

In this case, we ve specified the keys as name, age, and city, and the value as Unknown . The resulting array has the specified keys and the value Unknown .

19 Views