PHP array_fill_keys: The Complete Guide

0
36
PHP array_fill_keys() Function | How To Fill Array Keys In PHP

The array_fill_keys() function fills an array with values, specifying keys.

PHP array_fill_keys

PHP array_fill_keys() is a built-in function that fills an array with values, specifying keys. The array_fill_keys() function is used to create the new array filled with the given keys and value provided as the array to a function.

Syntax

See the following syntax.

array_fill_keys(keys, value)

Parameters

The keys are the required parameter, an array of values used as keys. This parameter is the array consisting of keys that are to be used to create the new array. If the $keys array contains any illegal value, it is converted into the string and used.

The value parameter is required and defines the value to use for filling the array. This parameter can be a single value or a list of values.

This parameter represents the value of the keys to be inserted into the array.

If this parameter is an array, the new array created will be a 2-d array where each element of the $keys array will be a key, and every key in this new array will have a $value array as a value.

Example

See the following code.

<?php

$keys = array("001","011","008","021");
$result = array_fill_keys($keys, "eleven");
print_r($result);

See the output.

➜  pro php app.php
Array
(
    [001] => eleven
    [011] => eleven
    [008] => eleven
    [021] => eleven
)
➜  pro

If an associative array is used as the second parameter of array_fill_keys, then the associative array will be appended to all the first array values.

See the code.

<?php

$array1 = array(
    "a" => "ariana",
    "t" => "taylor",
    "s" => "selena",
);

$array2 = array(
    "m" => "Michael",
    "e" => "Ed",
    "d" => "Drake");

print_r(array_fill_keys($array1, $array2));

See the output.

➜  pro php app.php
Array
(
    [ariana] => Array
        (
            [m] => Michael
            [e] => Ed
            [d] => Drake
        )

    [taylor] => Array
        (
            [m] => Michael
            [e] => Ed
            [d] => Drake
        )

    [selena] => Array
        (
            [m] => Michael
            [e] => Ed
            [d] => Drake
        )

)
➜  pro

That’s it for this tutorial.

Recommended Posts

PHP array_udiff()

PHP array_product()

PHP array_column()

PHP ksort()

PHP array_reverse()

Leave A Reply

Please enter your comment!
Please enter your name here

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