Understanding PHP's array_fill() Function: Usage, Parameters, Return Values, and Examples
This article explains PHP's array_fill() function, detailing its purpose, parameters, return behavior, and provides clear code examples—including simple and two‑dimensional array fills—to help developers quickly master array creation and population in backend development.
PHP is a widely used language for web development, and its built-in functions, such as array_fill() , help improve code readability, maintainability, and reusability. This guide introduces the array_fill() function, explains how it works, and provides practical examples.
1. Function Overview
The array_fill() function fills an array with a specified value. It requires 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 for filling, 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
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. Simple Example
Below is a basic example that creates a one‑dimensional array filled with the value 10 :
<?php
$array1 = array_fill(0, 5, 10);
print_r($array1);
?>Output:
Array ( [0] => 10 [1] => 10 [2] => 10 [3] => 10 [4] => 10 )5. Two‑Dimensional Example
The following example creates a 3×3 matrix where each element is 1 by nesting array_fill() calls:
<?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 ) )This demonstrates how array_fill() can be used to generate multi‑dimensional arrays by supplying an array as the fill value.
6. Summary
The array_fill() function enables developers to quickly create arrays populated with a uniform value, simplifying tasks such as initializing data structures. Properly setting its parameters and understanding its return behavior are essential for effective use in PHP programming.
Practicing with various examples will help solidify understanding and improve overall coding skills.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.