array_fill_keys

(no version information, might be only in CVS)

array_fill_keys -- Fill an array with values, specifying keys

Description

array array_fill_keys ( array keys, mixed value )

array_fill_keys() fills an array with the value of the value parameter, using the values of the keys array as keys.

例 1. array_fill_keys() example

<?php
$keys
= array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

$a now is:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

See also array_fill() and array_combine().


add a note add a note User Contributed Notes
php dot spam at phihag dot de
05-Jan-2007 10:44
A better(presumably faster, easier to write) substitute (for php >= 5) is:

<?php
if (! function_exists("array_fill_keys")) {
   function
array_fill_keys(array $keys, $value) {
       return
array_combine($keys, array_fill(0, count($keys), $value));
   }
}

// simple testcase
(array_fill_keys(array(1, 3, 2, "a", "b"), 42) === array(1 => 42, 3 => 42, 2 => 42, "a" => 42, "b" => 42)) or die("testcase 1 of array_fill_keys failed.");
?>
bananasims at hotmail dot com
19-Dec-2006 01:03
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below

function array_fill_keys($array, $values) {
   if(is_array($array)) {
       foreach($array as $key => $value) {
           $arraydisplay[$array[$key]] = $values;
       }
   }
   return $arraydisplay;
}