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:

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

Output:

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

Two‑dimensional array example:

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

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.