166 of 410 menu

The array_fill Function

The array_fill function creates an array filled with elements of a specific value.

Syntax

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

Example

Let's fill an array with 5 elements with the text 'x'. Since the first parameter is 0, the keys will start numbering from zero:

<?php $res = array_fill(0, 5, 'x'); var_dump($res); ?>

Code execution result:

[0 => 'x', 1 => 'x', 2 => 'x', 3 => 'x', 4 => 'x']

Example

Let's fill an array with 5 elements with the text 'x'. Since the first parameter is 3, the keys will start numbering from three:

<?php $res = array_fill(3, 5, 'x'); var_dump($res); ?>

Code execution result:

[3 => 'x', 4 => 'x', 5 => 'x', 6 => 'x', 7 => 'x']

Example

Let's fill a two-dimensional array:

<?php $res = array_fill(0, 3, array_fill(0, 3, 'x')); var_dump($res); ?>

Code execution result:

[['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']]

See Also

  • the array_pad function,
    which pads an array with specified elements
  • the range function,
    which creates an array with a range of elements
byenru