Backend Development 2 min read

PHP array_fill() Function: Fill an Array with a Specified Value

This article explains PHP's array_fill() function, detailing its syntax, parameters, return value, and providing example code that demonstrates how to create arrays filled with a specified value, including handling of start indexes and negative indices.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP array_fill() Function: Fill an Array with a Specified Value

The array_fill() function in PHP fills an array with a given value for a specified number of entries, using the $start_index parameter to set the first index of the returned array.

Syntax

array_fill(int $start_index, int $num, mixed $value)

Parameters

start_index : The index of the first element in the returned array. If negative, the first index will be the negative value and subsequent indexes start from 0.

num : The number of elements to insert; must be greater than 0.

value : The value used to fill the array.

Return value

Returns the array after it has been filled with the specified value.

Example

<?php
$a = array_fill(5, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a);
print_r($b);
?>

Output

Array
(
    [5] => banana
    [6] => banana
    [7] => banana
    [8] => banana
    [9] => banana
    [10] => banana
)
Array
(
    [-2] => pear
    [-1] => pear
    [0] => pear
    [1] => pear
)
backendProgrammingPHPTutorialfunctionarray_fill
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.