array_fill() Function in PHP

array_fill() creates an array with a specified number of elements, all set to the same value.

Version Support: array_fill() in PHP 8.5, array_fill() in PHP 8.4, array_fill() in PHP 8.3, array_fill() in PHP 8.2, array_fill() in PHP 8.1, array_fill() in PHP 7.1, array_fill() in PHP 7.2, array_fill() in PHP 7.3, array_fill() in PHP 7.4

Syntax:

array_fill(int $start_index, int $count, mixed $value): array

→ $start_index: Index of the first element.
→ $count: Number of elements to create (must be 0 or greater).
→ $value: Value assigned to every element.

Example:

$items = array_fill(0, 4, "Hello");

print_r($items);

Output:

Array
(
   [0] => Hello
   [1] => Hello
   [2] => Hello
   [3] => Hello
)

The starting index can also be negative:

$numbers = array_fill(5, 3, 10);
// [5 => 10, 6 => 10, 7 => 10]

If $count is 0, the result is an empty array. Note that objects used as $value are repeated by reference, so each array element refers to the same object.

22 Views