array_fill_keys()
This function acts similar to array_fill() but is different in that you specify the keys to use instead of simply creating a numerically keyed array.
Since you are suppling the keys, you do not need to tell it how many elements to make (it will use all of the keys) and you do not need to tell it where to start; just give it the list of keys and the value to use for each one and off it goes.
As an example, here’s how those two functions can produce the same output.
$arr1 = array_fill(5, 17, 'Q'); // start with key of 5, make 17 elements $arr2 = array_fill_keys(range(5, 22), 'Q'); // for keys, use an array of 5-22 (has 17 elements)
$keys = array('first', 'another', 42, 'this_one'); $arr = array_fill_keys($keys, 'X'); /* array ( 'first' => 'X', 'another' => 'X', 42 => 'X', 'this_one' => 'X' ) */
In your array of keys to use, a string which is an integer value will be converted to that integer value (even negative numbers). Boolean false will become an empty string, true will become integer one (1). Duplicate keys will be ignored.
$keys = array('first', 'another', 0, false, true, '87', '-4', 1, '42.5', 'this_one'); $arr = array_fill_keys($keys, 'X'); /* array ( 'first' => 'X', 'another' => 'X', 0 => 'X', '' => 'X', 1 => 'X', 87 => 'X', -4 => 'X', '42.5' => 'X', 'this_one' => 'X' ) */
