In the PHP function library, the array_fill() function is a very useful function, used to fill an array with a specified number of elements, and at the same time, you can specify the key and value of the filled elements. This article will introduce how to use the array_fill() function.
array_fill(int $start_index, int $num, mixed $value): array
Parameter explanation:
$start_index: The starting index of the array, must be a non-negative integer.
$num: The number of elements to be filled in the array, must be a non-negative integer.
$value: The filled value can be any basic type or composite type, but it must be a scalar value.
Explanation of return value:
Returns an array containing elements filled in the specified range.
The following is a sample code using the array_fill() function:
<?php // 填充10个元素的值为1的数组 $arr = array_fill(0, 10, 1); print_r($arr); ?>
Output result:
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [9] => 1 )
In In this example, we create an array and fill it with 10 elements using the array_fill() function, with the value of each element being 1. The starting index is 0 and the number of elements to fill is 10. Since we didn't specify a key name, the function will use a numeric index by default.
We can also specify non-numeric key names, as in the following example:
<?php // 使用字母作为键名填充数组 $arr = array_fill('a', 5, 'hello'); print_r($arr); ?>
Output results:
Array ( [a] => hello [b] => hello [c] => hello [d] => hello [e] => hello )
In this example, we use letters as key names, filled with 5 elements, the value of each element is the string 'hello'.
When using the array_fill() function, you need to pay attention to the following points:
The array_fill() function is a very useful function that can quickly fill an array and avoid the tedious operation of manual loop filling. Its use is very simple, you only need to specify the starting index of the array, the number of filling elements and the filling value. When using it, you need to pay attention to the correctness of the parameters to avoid abnormal operation of the function due to incorrect parameters.
The above is the detailed content of Introduction to how to use the array_fill() function in the PHP function library. For more information, please follow other related articles on the PHP Chinese website!