When filling an array with array_fill(), which value does the key of the array start from? How to determine the key value?
In PHP, the array_fill() function is a very convenient tool that allows you to fill an array with specified values. The basic syntax of this function is as follows:
array_fill(int $start_index, int $num, mixed $value): array
$start_index : Specifies the array key (index) to start filling;
$num : Specifies the number of elements to be filled;
$value : The value to be filled.
But a common question is, when using array_fill() to fill an array, which value does the key of the array start from? And, how does PHP determine the key value?
First, array_fill() allows us to fill the array starting with any given key (index), rather than starting from zero. That is, the starting value of the key is determined by the $start_index parameter you provide.
For example, consider the following code:
<?php
$array = array_fill(5, 3, "hello");
print_r($array);
?>
Output:
Array
(
[5] => hello
[6] => hello
[7] => hello
)
As you can see from the example above, the array starts with the key value 5 and then increases by 1 in turn (i.e. 6, 7, etc.). Therefore, the key value of the array starts with the value specified by $start_index .
When array_fill() fills an array in PHP, the value of the key is determined according to the following rules:
Start key : provided by the first parameter $start_index of array_fill() . This is the start key when filling the array.
Increment method : The key will automatically increment. Even if the array is filled with the same value, the key will still increase one by one from $start_index . The specific method of incrementing is to increment in integer order ( $start_index + 1, $start_index + 2, etc.).
Negative keys : If the $start_index you provide is a negative number, PHP will fill it according to the negative keys. For example:
<?php
$array = array_fill(-2, 3, "world");
print_r($array);
?>
Output:
Array
(
[-2] => world
[-1] => world
[0] => world
)
In this case, the key value of the array starts at -2 and is incremented to -1, 0.
Non-integer keys : array_fill() only supports integer keys. If you try to use non-integer keys, it will automatically convert to integer keys. For example:
<?php
$array = array_fill("a", 3, "test");
print_r($array);
?>
This code throws a warning that $start_index must be an integer. To avoid this, make sure the $start_index parameter is passed a valid integer.
When array_fill() fills an array, the key of the array is specified by the $start_index parameter. Starting from this key, the keys of the array will gradually increase. If $start_index is a negative number, the key will also be a negative number, and incrementing follows the negative number rule. It should be noted that array_fill() always increments the key value by integer, no matter what the value you fill is.