An array is a data structure that stores an arbitrary number of values in a single value. An array in PHP is actually an ordered map, where map is a type that associates values to keys.
Initializing an Array
An array can be initialized empty:
An array can be initialized and preset with values:
An array can also be initialized with custom indexes (also called an associative array):
If the variable hasn't been used before, PHP will create it automatically. While convenient, this might make the code harder to read:
The index will usually continue where you left off. PHP will try to use numeric strings as integers:
To initialize an array with fixed size you can use SplFixedArray:
Note: An array created using SplFixedArray has a reduced memory footprint for large sets of data, but the keys must be integers.
To initialize an array with a dynamic size but with n non empty elements (e.g. a placeholder) you can use a loop as follows:
Conclusion: With array_fill() you are more limited for what you can actually do. The loop is more flexible and opens you a wider range of opportunities.
Whenever you want an array filled with a range of numbers (e.g. 1-4) you could either append every single element to an array or use the range() function:
array range ( mixed $start , mixed $end [, number $step = 1 ] )
This function creates an array containing a range of elements. The first two parameters are required, where they set the start and end points of the (inclusive) range. The third parameter is optional and defines the size of the steps being taken. Creating a range from 0 to 4 with a stepsize of 1, the resulting array would consist of the following elements: 0, 1, 2, 3, and 4. If the step size is increased to 2 (i.e. range(0, 4, 2)) then the resulting array would be: 0, 2, and 4.
range can work with integers, floats, booleans (which become casted to integers), and strings. Caution should be taken, however, when using floats as arguments due to the floating point precision problem.