array_fill()
This function will create an array and initialize the elements with the value of your choosing. The resulting array will be numerically indexed.
You specify the starting index, the number of elements the array will contain, and the value to be used for each of those elements.
This can be useful for initializing an array before merging other data with it so that each key will have a value associated with it instead of ending up with “holes” in the array by having some not being set.
$arr = array_fill(4, 3, 'monkey'); /* array ( 4 => 'monkey', 5 => 'monkey', 6 => 'monkey' ) */ $arr = array_fill(0, 5, 17); /* array ( 0 => 17, 1 => 17, 2 => 17, 3 => 17, 4 => 17 ) */
The value may be any type that could be placed in an array.
$arr = array_fill(8, 3, false); /* array ( 8 => false, 9 => false, 10 => false ) */ $val = array('apple', 'banana'); $arr = array_fill(3, 2, $val); /* array ( 3 => array ( 0 => 'apple', 1 => 'banana' ), 4 => array ( 0 => 'apple', 1 => 'banana' ) ) */ // a quick way to set up a multidimensional "grid" array $arr = array_fill(0, 5, array_fill(0, 5, 'Q')); // a 5x5 array with each element initialized to Q
The second parameter will be converted to an integer (decimals are truncated). If it is less than one, however, a warning will be given and false is returned. Keep in mind again how types are converted to integers.
If the first parameter is negative, the first element will have that negative key, but the second element will step to zero, then one, etc. This is the normal functionality of arrays.
$arr = array_fill(0, '2x', 'monkey'); /* array ( 0 => 'monkey', 1 => 'monkey' ) */ $arr = array_fill(-17, 4, 'X'); /* array ( -17 => 'X', 0 => 'X', 1 => 'X', 2 => 'X' ) */
