Backend Development 5 min read

Understanding PHP's array_fill() Function: Usage, Parameters, Return Values, and Examples

This article explains PHP's array_fill() function, detailing its purpose, three parameters, return behavior, and provides clear code examples for both one‑dimensional and two‑dimensional array creation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP's array_fill() Function: Usage, Parameters, Return Values, and Examples

1. Function Overview

The array_fill() function in PHP fills an array with a specified value, requiring three arguments: the start index, the number of elements, and the value to fill.

2. Function Parameters

The function accepts three parameters:

start_index : the starting index, must be a non‑negative integer.

num : the number of elements to fill, must be a non‑negative integer.

value : the value to assign to each element, can be of any type.

3. Return Value

array_fill() returns a new array containing the filled elements. If start_index or num is negative, the function returns false . If num is zero, an empty array is returned.

4. Code Examples

Example 1: Simple one‑dimensional array

<?php
    $array1 = array_fill(0, 5, 10);
    print_r($array1);
?>

Output:

Array ( [0] => 10 [1] => 10 [2] => 10 [3] => 10 [4] => 10 )

This creates an array of five elements, each set to 10 , starting at index 0 .

Example 2: Two‑dimensional array

<?php
    $array2 = array_fill(0, 3, array_fill(0, 3, 1));
    print_r($array2);
?>

Output:

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

Here the first array_fill() creates a sub‑array of three 1 s, and the outer call replicates this sub‑array three times, resulting in a 3×3 matrix filled with 1 s.

5. Summary

The array_fill() function provides a quick way to generate arrays with uniform values, useful for initializing data structures in PHP. Properly setting its parameters ensures correct array size and content, and understanding its return behavior helps avoid unexpected results.

backendPHPTutorialfunctionphp-arrayarray_fill
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.