The PHP array_fill is an inbuilt Function in PHP. It fills an array with values. It basically creates a user-defined array with the given value. In this article, we will discuss the PHP array_fill Function along with examples.
array_fill($startIndex, $numberOfElements, $values)
The PHP array_fill Function expects three mandatory parameters. The description of the parameters is as follows:
- $startIndex: The first parameter refers to the starting index of the array which you want to create. If it is negative, then the first index is negative followed by indices starting from 0. However, it is always better to assign a positive value to it.
- $numberOfElements: The second parameter refers to the number of elements in the new array. However, it should be a positive integer (0 is allowed as of PHP 5.6).
- $values: The third parameter refers to the values which we want to insert. Additionally, they can be of any type.
The PHP array_fill Function returns an array with values specified in the $values parameter. Also, it is of the size as per the user input parameters.
Let’s discuss a few examples of using the array_fill Function
Example 1: Single Dimensional Array
In order to create a single dimensional array in PHP, you can use the array_fill Function as follows:
<?php $array = array_fill(2, 5, 'Concatly'); print_r($array); /* Array (  => Concatly  => Concatly  => Concatly  => Concatly  => Concatly ) */ ?>
In the above code, we create a new array starting from index 2 and having 5 values.
Example 2: Negative Index
<?php $array = array_fill(-2, 5, 'Concatly'); print_r($array); /* Array ( [-2] => Concatly  => Concatly  => Concatly  => Concatly  => Concatly ) */ ?>
We can also create an arary starting with a negative index. However, the corresponding indices begin from 0.
Example 3: Initialise an Array with 0
The PHP array_fill is useful when you want to
<?php $array = array_fill(0, 5, 0); print_r($array); /* Array (  => 0  => 0  => 0  => 0  => 0 ) */ ?>
Example 4: Multi-Dimensional Array
You can also create multi-dimensional arrays using this function by nesting the functions inside another. This is demonstrated below:
<?php $array = array_fill(0, 2, array_fill(0, 2, 0)); print_r($array); /* Array (  => Array (  => 0  => 0 )  => Array (  => 0  => 0 ) ) */ ?>
This can be useful when initialising an array with 0 in PHP.
In conclusion, we discussed the PHP array_fill Function in this article. You can learn more about it on the Official Documentation of PHP. Also, you can read more about PHP Array Functions on Concatly.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.