Master PHP’s array_fill(): Quick Guide to Fill Arrays Efficiently
This article explains PHP’s array_fill() function, detailing its syntax, parameters, return values, and practical examples—including numeric and associative key usage—while highlighting important considerations such as non‑negative indices, scalar values, memory usage, and edge cases.
In PHP's function library, the array_fill() function is a useful tool for filling an array with a specified number of elements, allowing you to define both keys and values.
Function Signature
array_fill(int $start_index, int $num, mixed $value): arrayParameter Explanation
$start_index: The starting index of the array, must be a non‑negative integer. $num: The number of elements to fill, must be a non‑negative integer. $value: The value to fill, can be any scalar type; it must be a scalar.
Return Value
Returns an array containing the filled elements within the specified range.
Usage Examples
Example 1 – Fill an array with ten elements of value 1:
<?php
// Fill an array with 10 elements, each value 1
$arr = array_fill(0, 10, 1);
print_r($arr);
?>Output:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
)Example 2 – Use letters as keys:
<?php
// Use letters as keys to fill the array
$arr = array_fill('a', 5, 'hello');
print_r($arr);
?>Output:
Array
(
[a] => hello
[b] => hello
[c] => hello
[d] => hello
[e] => hello
)Important Notes
$start_indexmust be a non‑negative integer; otherwise a warning is raised. $num must be a non‑negative integer; otherwise a warning is raised. $value must be a scalar; using non‑scalar values triggers a warning.
When using alphabetic keys, ensure the sequence is correct to avoid misalignment.
If the number of elements is zero, the function returns an empty array.
Filling a very large number of elements may consume significant memory.
Conclusion
The array_fill() function provides a quick way to populate arrays without manual loops, requiring only the start index, number of elements, and the fill value. Proper parameter usage prevents errors and optimizes performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
