PHP array_fill_keys() Function

PHP array_fill_keys() function is “used to create a new array filled with the specified keys and values.”

Syntax

array_fill_keys($keys, $value)

Parameters

  1. $keys(required): It is an array of values that will become keys in the new array. If the keys array contains any illegal value, it is converted into the string and used.
  2. $value(required): It defines the value for filling the array. This parameter can be a single value or a list of values.

Return value

This function returns the filled array.

Visual RepresentationVisual Representation of PHP array_fill_keys() Function

 

Example 1: How to Use array_fill_keys() function

<?php

$keys = [1,11,21,31];

$result = array_fill_keys($keys, "eleven");

print_r($result);

Output

Array
(
  [1] => eleven
  [11] => eleven
  [21] => eleven
  [31] => eleven
)

In the example above, each element of the $keys array becomes a key in the $result array, and each of those keys is associated with the same value(eleven) provided.

Example 2

<?php

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

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

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

Output

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
 )

)

That’s it.

Leave a Comment

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