AppDividend
Latest Code Tutorials

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

0

PHP array_fill_keys() Function | How To Fill Array Keys In PHP is today’s topic. The array_fill_keys() function fills an array with values, specifying keys. The array_fill_keys() function is the builtin function in PHP and is used to create the new array filled with the given keys and value provided as the array to a function.

PHP array_fill_keys() Function

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

See the following syntax.

array_fill_keys(keys, value)

The keys are the required parameter, and it is an array of values that will be 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, then it is converted into the string and used.

The value parameter is required, and it 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 that are to be inserted into the array. If this parameter is an array, then the new array created will be a 2-d array where each element of $keys array will be a key, and every key in this new array will have $value array as a value.

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 in all the values of the first array.

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

Recommended Posts

PHP array_udiff() Function Example

PHP array_product() Function

PHP Array Column Example

PHP ksort Function Example

PHP array_reverse() Function Example

Leave A Reply

Your email address will not be published.

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