In PHP, the native array_fill() function can be used to fill the specified key range of an array with fixed values, which is simple in syntax and very efficient:
$filled = array_fill(0, 5, 'default');
// result: ['default', 'default', 'default', 'default', 'default']
However, sometimes we want the filled value not fixed, but dynamically generated by some kind of logic. For example, fill in incremental numerical values, UUIDs, random numbers, or custom structures generated based on the current key.
To achieve more flexible requirements, we can design an enhanced version of the array_fill() function: array_fill_advanced() . This function allows you to pass in a "default value callback function" to dynamically generate the corresponding value based on the key name.
Supports filling arrays of arbitrary lengths
The starting index can be customized (can be integer or string)
The value can be fixed or generated by a callback function.
The callback function accepts the current key index as a parameter
The following is the implementation of array_fill_advanced() :
/**
* Dynamically fill array
*
* @param int|string $startIndex Start key name
* @param int $count Number of fills
* @param mixed $valueOrCallback Fixed value or callback function
* @return array
*/
function array_fill_advanced($startIndex, int $count, $valueOrCallback): array {
$result = [];
// Determine whether the starting index is an integer
$isNumericIndex = is_int($startIndex);
for ($i = 0; $i < $count; $i++) {
$key = $isNumericIndex ? $startIndex + $i : $startIndex . $i;
if (is_callable($valueOrCallback)) {
$result[$key] = call_user_func($valueOrCallback, $key);
} else {
$result[$key] = $valueOrCallback;
}
}
return $result;
}
$data = array_fill_advanced(1, 3, 'hello');
// result: [1 => 'hello', 2 => 'hello', 3 => 'hello']
$data = array_fill_advanced(0, 5, function($index) {
return bin2hex(random_bytes(4));
});
// result: [0 => '9f3a4b2c', 1 => 'fa92be77', ...]
$data = array_fill_advanced('item_', 3, function($key) {
return strtoupper($key);
});
// result: ['item_0' => 'ITEM_0', 'item_1' => 'ITEM_1', ...]
$data = array_fill_advanced(0, 3, function($index) {
return [
'id' => $index,
'url' => "https://m66.net/resource/{$index}"
];
});
/*
result:
[
0 => ['id' => 0, 'url' => 'https://m66.net/resource/0'],
1 => ['id' => 1, 'url' => 'https://m66.net/resource/1'],
...
]
*/
array_fill_advanced() provides PHP developers with a more general, more powerful and more flexible array filling method. By introducing callback functions, we can not only reduce duplicate code, but also implement dynamic content construction based on key-value logic.
This is very useful in scenarios such as processing batch initialization data, constructing test samples, generating simulated API data, etc. Combining anonymous functions and flexible key name strategies, array_fill_advanced() can become a very practical gadget in your toolbox.