How to Fill an Array in PHP 


How to Fill an Array in PHP


In this article, we go over how to fill an array in PHP.

To fill an array means to load it with a certain number of elements of a specified value, such as:

all 100s: 100, 100, 100, 100, 100
all 50s: 50, 50, 50, 50, 50, 50, 50, 50, 50, 50

The reason why some languages such as PHP have a function to fill an array is to save time for the programmer. Say, if a programmer wants an array with 70 repeated 100 times in the array. Without the array_fill function, a programmer would have to manually type out '70' 100 times. This is tedious. With the array_fill function, we just type in '70' and how many times we want it repeated. This way, we save a lot of time programming.

To fill an array in PHP, we use the array_fill PHP function using the following general syntax:

$array_name= array_fill($start, $count, $value)

$start is the index at which the array starts
$count is the number of elements that is in the array
$value is the value of each of the elements in the array

So the array_fill function returns an array filled with $count $values starting at index $start.


So, to create an array that has 7 elements of the number 10 and starts at index 0, the PHP code to do this would be:

$array_name= array_fill(0, 7, 10) //10, 10, 10, 10, 10, 10, 10

PHP Output

10 10 10 10 10 10 10

So the array is filled with 7 10s.

HTML Comment Box is loading comments...