Intialise an array in PHP with default values

Posted in PHP -

PHP has a useful function for initialising an array with default values called array_fill(). This post looks at how to use the array_fill function and the output of these arrays with the print_r function.

The definition of this function in the PHP documentation is:

array array_fill ( int $start_index, int $num, mixed $value )

The $start_index value is the index you want to start filling the array from, the $num value the number of elements to insert into the array, and the $value the value to initialise each element with.

For example, if you wanted to initialise an array with 5 elements starting from 0 with a default value of 0 you would do this:

$array = array_fill(0, 5, 0);

Using print_r to output the values of the array would show this:

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
)

To initialise the same array starting with an index of 5, again with 5 elements, so you would have indexes from 5 to 9, you would do this:

$array = array_fill(5, 5, 0);

and the print_r output would look like this:

Array
(
    [5] => 0
    [6] => 0
    [7] => 0
    [8] => 0
    [9] => 0
)

You can fill the default values with anything you want. Here are some other examples:

$array = array_fill(0, 5, '');
$array = array_fill(0, 5, false);
$array = array_fill(0, 5, true);
$array = array_fill(0, 5, 'foo');

You can also fill the array using a variable. In the following example we create an array with 3 elements and then fill a new array with it:

$x = array(1,2,3);
$array = array_fill(0, 3, $x);

Doing print_r($array) will show this:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

This can be a useful function to use if you need to ensure there are values for elements X to Y when looping through the array later in the code using a for() loop, but your code only specifically puts values into some of the elements. If you hadn't inialised the array then there might be "holes" in it which would cause warnings to be issued when you try to access the element. Using array_fill at the start prevents this issue.



Related posts:


Comments