Using array_fill_keys() to Fill an Array with Specified Keys and Values in PHP

This article explains the PHP function array_fill_keys(), describing its purpose, parameters, return value, and provides a complete example with code and output to demonstrate how to create an array by assigning a common value to a set of specified keys.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_fill_keys() to Fill an Array with Specified Keys and Values in PHP

The article introduces the PHP function array_fill_keys(), which creates a new array by using the values of a given keys array as the array's keys and assigning a single specified value to each of those keys.

It explains that the value argument is used as the value for all entries, while the keys argument supplies the keys; any illegal key values are automatically converted to strings.

Parameters

keys : an array whose values will become the keys of the new array.

value : the value to assign to each key.

Return value

The function returns the newly created array populated with the specified keys and value.

Example

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

Output

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendArrayTutorialarray_fill_keys
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.