Backend Development 5 min read

Understanding PHP’s array_fill() Function: Syntax, Parameters, Return Values, and Examples

This article explains PHP’s array_fill() function, detailing its purpose, parameters (start_index, num, value), return behavior, and provides multiple code examples—including simple one-dimensional and nested two-dimensional array fills—to illustrate how to create and populate arrays efficiently.

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

PHP is a popular language for web development; its array_fill() function fills an array with a specified value.

1. Function Overview

The array_fill() function creates a new array by filling it with the same value, requiring three arguments: start_index , num , and value .

2. Parameters

start_index : the starting index (non‑negative integer).

num : the number of elements to fill (non‑negative integer).

value : the value to assign to each element (any type).

3. Return Value

The function returns the newly created array; if start_index or num is negative it returns false , and if num is zero it returns an empty array.

4. Examples

Simple one‑dimensional array:

Output:

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

Two‑dimensional array example:

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 ) )

5. Summary

The array_fill() function enables quick creation of arrays with uniform values, but careful attention to its parameters and return values is required for correct usage.

backendPHPcode examplesFunctionsarray_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.