PHP array_fill() Function

What is PHP array_fill() Function?

The array_fill() function creates an array filling a specified number of elements with a pre-defined value starting from a specified index number.

Syntax:

array_fill(starting_index, element_number, value)

Parameters:

The Function has 3 parameters; all are required-

starting_index (Required): It is an integer which specifies the first index of the resultant array.

element_number (Required): It is an integer which specifies the total number of elements in the resultant array. It should be greater than or equal to zero.

value (Required): It is a value (integer, string, boolean etc) which the function uses to fill the resultant array.

Return Values:

The function returns an array.

Examples:

Example 1:

<pre>
<?php
$array = array_fill(2, 4, 'PHP Function');
print_r($array);
?>
</pre>

Output:

Array
(
    [2] => PHP Function
    [3] => PHP Function
    [4] => PHP Function
    [5] => PHP Function
)

Example 2:

<pre>
<?php
$array = array_fill(-2, 4, 'PHP Function');
print_r($array);
?>
</pre>

Output:

Array
(
    [-2] => PHP Function
    [-1] => PHP Function
    [0] => PHP Function
    [1] => PHP Function
)

Example 3:

<pre>
<?php
$array = array_fill(2, 4, TRUE);
print_r($array);
?>
</pre>

Output:

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

Example 4:

<pre>
<?php
$array = array_fill(2, 4, ['PHP', 'MySQL']);
print_r($array);
?>
</pre>

Output:

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

PHP Version Support:

PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8

Summary: PHP array_fill() Function

If you want to create an array with a predefined value that starts with a specific index number and continues till a specific number of elements, use array_fill() function. It is a built-in array function in PHP.

Reference:

https://www.php.net/manual/en/function.array-fill.php