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

This article explains PHP's array_fill() function, detailing its purpose, parameters, return values, and provides simple and multi‑dimensional examples illustrating how to create and populate arrays with a single value, including edge cases such as negative indices and zero length.

php Courses
php Courses
php Courses
PHP array_fill() Function: Usage, Parameters, Return Values, and Examples

PHP is a widely used language for web development, and its functions enhance code readability, maintainability, and reusability. One useful function is array_fill(), which fills an array with a single value.

1. Function Overview

The array_fill() function creates a new array by filling each element with the same value. It requires three parameters: start index, number of elements, and the value to fill.

2. Parameters

The three parameters are: 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; it can be of any type.

3. Return Value

The function returns a new array containing the filled elements. If start_index or num is negative, it returns false. If num is zero, it returns an empty array.

4. Examples

Simple one‑dimensional example:

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

Output:

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

Two‑dimensional 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 ) )

The second example demonstrates nesting array_fill() to create a 3×3 matrix filled with the value 1.

5. Summary

The array_fill() function helps programmers quickly create an array and populate it with a uniform value, making it a valuable tool in PHP development. Proper understanding of its parameters and return values is essential for effective use.

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.

BackendPHPTutorialfunctionsarray 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.