Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3, PHP 8.4 With Latest All Version Support.
The array_fill() function in PHP creates an array filled with a specified value. It hasn’t changed significantly in PHP 8.1, PHP 8.2 & PHP 8.3, but here’s how to use it:
Syntax
array_fill(int $start_index, int $count, mixed $value): array
Parameters
$start_index: The first index of the returned array
$count: Number of elements to insert (must be ≥ 0)
$value: Value to use for filling
Examples
Basic usage
$filledArray = array_fill(0, 5, 'hello'); print_r($filledArray); /* Output: Array ( [0] => hello [1] => hello [2] => hello [3] => hello [4] => hello ) */
Starting from a negative index
$filledArray = array_fill(-3, 4, 'PHP'); print_r($filledArray); /* Output: Array ( [-3] => PHP [-2] => PHP [-1] => PHP [0] => PHP ) */
Creating a numeric array
$numbers = array_fill(1, 10, 0); print_r($numbers); /* Output: Array ( [1] => 0 [2] => 0 ... [10] => 0 ) */
array_fill() is particularly useful when you need to initialize an array with default values or create test data.