PHP array_fill()
Published Jul 12, 2023
Contribute to Docs
The array_fill() method is used to fill an array with values. This function creates a custom array with a given pre-filled value.
Syntax
array_fill($start_index, $number_elements, $values)
The array_fill() function has three required parameters:
$start_index: This parameter specifies the first index of the returned array.$number_elements: This parameter refers to the number of elements to insert into the array.$values: Specifies the values to be used to fill the array.
The array_fill() function returns a filled array.
Example
The following example uses the array_fill() function to add 3 elements of 'coffee' starting from index 5, to the indexed array $drink:
<?php$drink = array_fill(5, 3, 'coffee');print_r($drink);?>
The example will result in the following output:
Array ([5] => coffee[6] => coffee[7] => coffee)
Codebyte Example
This example is runnable and uses the array_fill() function:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours