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.
array_fill_keys($keys, $value)
$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.
<?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 operationprint_r($output1);print_r($output2);print_r($output3);?>
$key
values.array_fill_keys()
to fill the keys in $key1
with codes
as a value and push the outcome to the variable $output1
.array_fill_keys()
to fill the keys in $key2
with Edpresso
as a value and save the outcome to the variable $output2
.array_fill_keys()
to fill the keys in $key3
with life
as a value and store the outcome to the variable $output3
.array_fill_keys()
method used earlier in the code.