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:
- $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.
- $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.
- $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
function Fill( $start_index , $number_elements , $values ){
return ( array_fill ( $start_index , $number_elements , $values ));
}
$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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jun, 2023
Like Article
Save Article