Friday, October 24, 2025
HomeLanguagesPHP array_fill() function

PHP array_fill() function

The array_fill() is an inbuilt-function in PHP and is used to fill an array with values. This function basically creates an user-defined array with a given pre-filled value.

Syntax:

array_fill($start_index, $number_elements, $values)

Parameter:
The array_fill() function takes three parameters and are described below:

  1. $start_index: This parameter specifies the starting position of filling up the values into the array, the user wants to create. If $start_index is negative, the first index of the returned array will be $start_index and the following indices will start from zero. So it is better to assign a positive value to it. This is a mandatory parameter and must be supplied.
  2. $number_elements: This parameter refers to the number of elements, the user wants to enter into the array. The $number_elements should be positive (including 0, for ver 5.6.0) otherwise E_WARNING is thrown. This is also a mandatory parameter.
  3. $values : This parameter refers to the values we want to insert into the array. These values can be of any type.

Return Type: The array_fill() function returns a filled user-defined array, with values described by $value parameter.

Examples:

Input : $start_index = 2; $number_elements = 3;
        $values = "Geeks";
Output :
        Array
        (
          [2] => Geeks
          [3] => Geeks
          [4] => Geeks
        )

Input : $start_index = -10; $number_elements = 3;
        $values = 45;
Output :
        Array
        (
          [-10] => 45
          [0] => 45
          [1] => 45
        )

Below program illustrates the working of array_fill() function in PHP:




<?php
  
// PHP code to illustrate the working of array_fill()
  
function Fill($start_index, $number_elements, $values){
    return(array_fill($start_index, $number_elements, $values));
}
  
// Driver Code
$start_index = 2;
$number_elements = 5;
$values = "Geeks";
print_r(Fill($start_index, $number_elements, $values));
?>


Output:

Array
(
    [2] => Geeks
    [3] => Geeks
    [4] => Geeks
    [5] => Geeks
    [6] => Geeks
)

Reference: http://php.net/manual/en/function.array-fill.php

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS