What is the array_fill_keys() function in PHP?

Overview

The array_fill_keys() method will fill the same value for all the indicated keys of an array. Say we have an array, $keys = (3,"pin","tin"), and we want to use its values as a key for another array $fill = []. We can simply fill the keys with a new value like this:

$fill = array_fill_keys($keys,"value")

The above operation will produce an output like this:

(
3=>"value",
"pin"=>"value",
"tin"=>"value"
)

Note: The array_fill_keys() method in PHP has support for PHP version 5 and later.

Syntax

array_fill_keys($keys, $value)

Parameters

  • $keys: This is an array of values that will serve as the keys to the supplied values. The illegal members of this array will be converted to a string.

  • $value: This is the value that will be used to fill the keys with another value. That is, each key in the array $key will be given this value.

Example

<?php
//declare variables
$keys1 = array(1,2,3);
$keys2 = ["byte","size", "shots"];
$keys3 = [3,"play", 5,"laugh"];
//save output of operation in a value
$output1 = array_fill_keys($keys1,"codes");
$output2 = array_fill_keys($keys2,"Edpresso");
$output3 = array_fill_keys($keys3,"life");
//print all outcome from operation
print_r($output1);
print_r($output2);
print_r($output3);
?>

Explanation

  • Lines 3–5: We declare arrays which will be used as $key values.
  • Line 8: We use array_fill_keys() to fill the keys in $key1 with codes as a value and push the outcome to the variable $output1.
  • Line 9: We use array_fill_keys() to fill the keys in $key2 with Edpresso as a value and save the outcome to the variable $output2.
  • Line 10: We use array_fill_keys() to fill the keys in $key3 with life as a value and store the outcome to the variable $output3.
  • Lines 13–15: We display the output variables to show the return value of the array_fill_keys() method used earlier in the code.

Free Resources