In PHP, array_fill_keys() is a very useful function that creates a new array and fills the specified key name with the same value. The syntax of this function is as follows:
array_fill_keys(array $keys, mixed $value): array
$keys : an array containing key names.
$value : The value specified for each key name.
Suppose we have a simple example:
$keys = ['a', 'b', 'c'];
$value = 1;
$result = array_fill_keys($keys, $value);
print_r($result);
The output will be:
Array
(
[a] => 1
[b] => 1
[c] => 1
)
This example is simple. array_fill_keys() creates a new array based on the provided key names a , b , c and the specified value 1 .
However, the problem is that when the $keys array passed to array_fill_keys() contains duplicate key names, the function ignores these duplicate key names and only retains the last key-value pair that appears.
For example, look at the following code:
$keys = ['a', 'b', 'a', 'c'];
$value = 1;
$result = array_fill_keys($keys, $value);
print_r($result);
You might expect the result to contain duplicate a key, but in fact it would look like this:
Array
(
[a] => 1
[b] => 1
[c] => 1
)
In this example, the key name a is repeatedly passed into array_fill_keys() , but the result of the array only retains one key a and its value is 1 . This behavior is because the key names of the array are unique in PHP, so repeated key names are ignored, leaving only the last key that appears.
This behavior can be explained by the internal implementation of PHP arrays. In PHP, the key names of the array are unique. When array_fill_keys() creates a new array, it actually binds each key name to the specified value, and if there are duplicate key names, it only retains the last occurrence of the key name. This is to avoid duplicate keys in the array, because PHP's array does not allow the same key names to appear twice.
If you want to avoid this problem and make sure there are no duplicate key names in the $keys passed to array_fill_keys() , you can first use array_unique() to remove duplicate key names:
$keys = ['a', 'b', 'a', 'c'];
$value = 1;
$uniqueKeys = array_unique($keys);
$result = array_fill_keys($uniqueKeys, $value);
print_r($result);
The output will be:
Array
(
[a] => 1
[b] => 1
[c] => 1
)
This way, we ensure that only unique key names are used to fill the new array.
array_fill_keys() is a very convenient function, but if the passed key name array contains duplicate key names, it ignores the duplicate part and only retains the last key-value pair that appears. This behavior is part of the PHP array design, which ensures the uniqueness of the key name of the array. If you need to deal with the issue of duplicate key names, you can remove duplicate keys through array_unique() to ensure that each key name is unique.
Hopefully this article helps you better understand the array_fill_keys() function and its behavior when encountering duplicate key names. If you have any other questions, you can ask any questions at any time!