The array_fill_keys is an inbuilt Function in PHP. It fills an array with values, also specifying the keys. Also, it works similarly to the PHP array_fill Function. In this article, we will discuss the PHP array_fill_keys Function. Also, we will discuss a few examples of using it.
array array_fill_keys ( $keys, $value )
The PHP array_fill_keys Function expects two mandatory parameters. The description of the parameters is as follows:
- $keys: The first parameter is a mandatory array consisting of keys that will be used in creating the new array.
- $value: The second parameter is the mandatory value. If this parameter is a single value, then the new array contains this value in all the keys defined before. However, if this value is an array, then all the keys contain this array as values.
The PHP array_fill_keys Function returns an array containing the key-value pair according to the parameters.
Let’s discuss a few examples of using the array_fill_keys function.
Example 1: Single Value Input
For instance, consider a single value input to the function.
<?php $keys = array('apple', 5, '10', 'mango'); $value = 'fruits'; $array = array_fill_keys($keys, $value); print_r($array); /* Array ( [apple] => fruits  => fruits  => fruits [mango] => fruits ) */ ?>
In the above example, the $keys array contain mixed values (both string and keys). The final array has the $value to all the keys in the new array.
Example 2: Array as $value
You can also pass an array in the $value parameter.
<?php $keys = array('apple', 5, '10'); $value = array('vegetables', 'fruits'); $array = array_fill_keys($keys, $value); print_r($array); /* Array ( [apple] => Array (  => vegetables  => fruits )  => Array (  => vegetables  => fruits )  => Array (  => vegetables  => fruits ) ) */ ?>
As you can observe, the new array consists of the value array to all the keys as in the $keys array.
<?php $keys = array('apple', 5, '10'); $value = 'fruits'; $array = array_combine($keys,array_fill(0,count($keys),$value)); print_r($array); /* Array ( [apple] => fruits  => fruits  => fruits ) */ ?>
In conclusion, we discussed the PHP array_fill_keys Function. Also, you can read more about it on the Official Documentation. You can also read about array_fill Function which is similar to this function. You might also be interested in other PHP Array Functions.
Vishesh is currently working as a Senior Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.