In PHP, array_fill() is a very practical function to create an array with default values. However, one limitation of it is that arrays can only be filled based on numeric indexes , and the use of string keys (i.e. associative arrays) is not supported. So, what should we do if we want to use an array_fill() -like method to initialize an associative array with a specified key name?
This article will explain how to encapsulate a custom function to support batch initialization of associated key values.
Let's first look at how the standard array_fill() works:
$filled = array_fill(0, 3, 'default');
print_r($filled);
The output result is:
Array
(
[0] => default
[1] => default
[2] => default
)
You can see that it only supports numeric keys, populating the specified number of elements from the starting index.
Suppose we have a predefined set of key names, as follows:
$keys = ['username', 'email', 'age'];
We want to initialize them at once to a unified default value, such as 'N/A' , and generate the following structure:
[
'username' => 'N/A',
'email' => 'N/A',
'age' => 'N/A'
]
Although PHP has built-in array_fill_keys() function to achieve this goal, for teaching purposes, we will encapsulate a more extensible version ourselves:
/**
* Use the specified key array and value,Initialize an associative array
*
* @param array $keys Array of key names to use
* @param mixed $value Default value for each key
* @return array Initialized associative array
*/
function array_fill_keys_custom(array $keys, $value): array {
$result = [];
foreach ($keys as $key) {
$result[$key] = $value;
}
return $result;
}
$fields = ['username', 'email', 'age'];
$defaultValue = 'N/A';
$initializedArray = array_fill_keys_custom($fields, $defaultValue);
print_r($initializedArray);
Output result:
Array
(
[username] => N/A
[email] => N/A
[age] => N/A
)
We can also extend this function to support dynamically generating different values based on the key name, such as using a callback function:
function array_fill_keys_callback(array $keys, callable $callback): array {
$result = [];
foreach ($keys as $key) {
$result[$key] = $callback($key);
}
return $result;
}
$keys = ['token', 'session_id', 'timestamp'];
$data = array_fill_keys_callback($keys, function($key) {
switch ($key) {
case 'token':
return bin2hex(random_bytes(8));
case 'session_id':
return uniqid('sess_', true);
case 'timestamp':
return date('Y-m-d H:i:s');
default:
return null;
}
});
print_r($data);
Output example (may be different for each run):
Array
(
[token] => 9f3a8f734b23f9cd
[session_id] => sess_6623fa3890adf3.20534250
[timestamp] => 2025-04-20 13:52:43
)
This encapsulation is ideal for form field initialization, API return template generation, or default configuration array construction. For example, when you construct the default return of the REST API:
$responseTemplate = array_fill_keys_custom(['code', 'message', 'data'], null);
$responseTemplate['code'] = 200;
$responseTemplate['message'] = 'Operation is successful';
$responseTemplate['data'] = ['url' => 'https://m66.net/api/example'];
print_r($responseTemplate);
Although PHP provides some ready-made array functions (such as array_fill_keys() ), through custom encapsulation, we can implement more flexible initialization methods, especially when dealing with associative arrays.
This method not only has more elegant code, but also improves your control over array operation logic. It will be a very useful gadget in real projects, especially when it is necessary to generate large amounts of structured data dynamically.