What is the array_fill() method in PHP?

Overview

The length of an array might be especially important when we carry out length-dependent evaluations. For reasons like this, functions like array_fill() come in very handy, especially to build an array of the required length. We may have a length that is less than the length needed for evaluation/comparison.

The array_fill() method fills up an array to a required length just like array_pad(). However, unlike array_pad(), it can do this from a specific index number. This implies that it does not just fill an array to a specified length, it will do it from a specific point.

For instance, we have an array variable A = [] and we want to fill up A to the size of 5, starting from index point 2 using Y. Passing A to the array_fill() will cause A to be returned as A = ["Y","Y","Y","Y","Y"].

Using a function like var_dump() or print_r() to investigate array A, we’ll find out that the first index of A will be 2. See more about this example in the code snippet below.

Syntax

array_fill($start_index,$count,$filler)

Parameters

  • start_index: This is an integer, which indicates the index value to determine the first index in the return array.

  • $count: This is the number of times the $filler value will be inserted into the array. It is an integer. It can’t be 0 or negative, otherwise the program will throw an error.

  • $filler: The value which will be inserted into the array $count number of times. It can be of any data type.

Return value

An array that has been filled up with the provided element will be returned.

Code

The code snippet below is an illustration of how to use this method. The sample array A used above will be filled up using the method in the snippet below.

<?php
//declare empty array
$A = [];
//fill up the empty array
$A = array_fill(2,5,"Y");
//using print_r() to see the details of the array
print_r($A);
// fill up the array $fillable with lemon
$fillable = array_fill(6,4,'lemon');
//first index of returned array will be negative
$arrayVal = array_fill(-4, 4, 'pear');
//print the output to the screen
print_r($fillable);
print_r($arrayVal);
?>

Explanation

  • Line 3: We declare an empty array.

  • Line 5: We fill up the empty array using the array_fill() method.

  • Line 7: We use the print_r() to see the details of the array.

  • Line 10: We fill up the array $fillable with lemon.

  • Line 12: We fill up an array where the first member will be negative.

  • Lines 15 and 16: We print the result using the array_fill() method on lines 10 and 12.

Free Resources