PHP array_fill_keys() Function

Last Updated on October 29, 2021 by Roshan Parihar

PHP array_fill_keys() Function is used to fill an array with the given keys and the specified values in a function. After the use of the function, the previous array items are considered as the keys that are combine with the values specified in a function.

Let’s find out the use of the PHP array_fill_keys() function with the examples given below.

Syntax of PHP array_fill_keys() Function

array_fill_keys(keys, value)

The array_fill_keys() function takes comma-separated keys and the value as an argument.

Description of Parameters

Name Description
keys Required. It is the array with values that are considered as keys for the new array created after using the function. If it contains any illegal value, it will be converted into a string to use for the new array.
value Required. Specify the single or multiple values for the keys to insert into the new array.

Let’s find out the use of the PHP array_fill_keys() Function with the examples given below.

Examples of PHP array_fill_keys() Function

See the examples given below to learn how to fill an array with the given keys and the specified value using the array_fill_keys() Function in PHP.

Example 1: Fill Keys with Specified Values in PHP

Suppose that, if you have an array that contains 4 items. When you use the PHP array_fill_keys() function and specify a value inside it, these 4 items are considered as the keys for the new array combines with the specified value.

Output

Array ( [Bike] => Red [Cycle] => Red [Car] => Red [WagonR] => Red )

The above output shows that the all the items of the array are combined with the specified value to create a new array in PHP.

Example 2: Fill Keys with Multiple Values

If you want to fill multiple values to each key to create a new array in PHP, you can use an array as the second argument of the PHP array_fill_keys() function. Every single item of the first array combines with all the items of the second array to create a new array in PHP.

Output

Array ( [Bike] => Array ( [0] => 2 [1] => 5 ) [Cycle] => Array ( [0] => 2 [1] => 5 ) [Car] => Array ( [0] => 2 [1] => 5 ) [WagonR] => Array ( [0] => 2 [1] => 5 ) )

The above example shows a new array created by combining a single item of the first array with all the items of the second array.

Example 3: Fill Created Keys Using Range() with Values

In addition to the above example, you can also fill created keys using the range() function. It creates a list of items that are considered as keys to combine with the specified value in the PHP array_fill_keys() function.

Output

Array ( [0] => Bike [1] => Bike [2] => Bike [3] => Bike )

The above example shows the array created by combining the keys with the specified value.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.