In daily development of PHP, we often encounter situations where we need to quickly generate a predefined array, such as initializing an array with a specified length and the default values are consistent. At this time, the array_fill() function is your good helper! This article will use the shortest time to let you fully understand this efficient and practical function.
array_fill() is a built-in array processing function in PHP. It can be used to create an array of specified size and values. Its syntax is as follows:
array_fill(int $start_index, int $count, mixed $value): array
$start_index : The index of the first element in the new array, which can be an integer (including negative numbers).
$count : The number of elements to be filled.
$value : The value to be filled.
$arr = array_fill(0, 10, 0);
print_r($arr);
Output:
Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
)
This example generates an array starting with index 0, length 10, and values all 0.
$default_settings = array_fill(0, 5, 'off');
You can easily use it to indicate that the 5 switches are initially closed.
Suppose there are 10 options in a multi-select form, and you want to default to false before the user submits:
$form_defaults = array_fill(1, 10, false);
$placeholders = array_fill(0, 3, 'loading...');
This type of array can be used for front-end template output, and the default prompt is displayed when data is loaded.
If $count is less than or equal to 0, an empty array is returned.
If $start_index is negative, the keys of the array will also be negative.
This function does not retain the key name structure, only keys are generated in order.
// Negative index example
$arr = array_fill(-3, 3, 'PHP');
print_r($arr);
Output:
Array
(
[-3] => PHP
[-2] => PHP
[-1] => PHP
)
You may generate default values for URL parameters in some dynamic scenarios. For example, you want to generate the default page number of 5 paging links:
$page_links = array_fill(1, 5, 'https://m66.net/page/1');
foreach ($page_links as $key => $url) {
$page_links[$key] = "https://m66.net/page/{$key}";
}
print_r($page_links);
Output:
Array
(
[1] => https://m66.net/page/1
[2] => https://m66.net/page/2
[3] => https://m66.net/page/3
[4] => https://m66.net/page/4
[5] => https://m66.net/page/5
)
Isn't it very practical?
array_fill() is a simple but powerful function that is used to quickly initialize arrays. Whether it is development configuration, forms, data processing, or paging logic, it can greatly improve your development efficiency. Now, it only takes 5 minutes to fully master it!
Next time you need to create a bunch of default values, stop manually filling the array with loops, use array_fill() to make your code clearer and more efficient!