In development, we often need to set unified default values for a set of key names, especially in scenarios where cache, configuration initialization, or data normalization are performed. PHP's built-in array_fill_keys() function can solve this problem very elegantly, helping us reduce redundant code, improve code readability and execution efficiency.
This article will use the default value of the cache structure as an example to explain how to use array_fill_keys() to achieve this goal.
array_fill_keys() is an array function provided by PHP to fill the specified keys in the array with the specified value.
Function definition:
array array_fill_keys(array $keys, mixed $value)
$keys : an array containing all key names.
$value : The default value to assign to each key.
Example:
$keys = ['user_1', 'user_2', 'user_3'];
$defaultValue = null;
$cache = array_fill_keys($keys, $defaultValue);
print_r($cache);
Output:
Array
(
[user_1] =>
[user_2] =>
[user_3] =>
)
Imagine a typical scenario: you are building a system cache structure where you need to batch initialize the cached data according to the user ID to a predefined array, for example:
$defaultCacheValue = [
'profile' => null,
'settings' => [],
'last_login' => null,
];
You have multiple user IDs:
$userIds = [101, 102, 103, 104];
If you initialize these structures manually, it will become lengthy and difficult to maintain. Use array_fill_keys() to do it easily:
$keys = array_map(function ($id) {
return "user_cache_$id";
}, $userIds);
$cacheStructure = array_fill_keys($keys, $defaultCacheValue);
print_r($cacheStructure);
Output result:
Array
(
[user_cache_101] => Array
(
[profile] =>
[settings] => Array
(
)
[last_login] =>
)
[user_cache_102] => Array
(
[profile] =>
[settings] => Array
(
)
[last_login] =>
)
...
)
If your user ID is obtained from the database or API, you can also use array_column() and other functions to dynamically handle it:
// Assume from API Returns the following structure
$userData = [
['id' => 201, 'name' => 'Alice'],
['id' => 202, 'name' => 'Bob'],
['id' => 203, 'name' => 'Charlie'],
];
$userIds = array_column($userData, 'id');
$keys = array_map(function ($id) {
return "user_cache_$id";
}, $userIds);
$defaultCache = [
'profile_url' => 'https://m66.net/user/default',
'status' => 'offline',
'messages' => [],
];
$cache = array_fill_keys($keys, $defaultCache);
print_r($cache);
Note for immutable structures : If you modify the default value of the padding, it will affect all keys because the array refers to the same structure. If you want each key to have an independent structure, you need to copy it manually:
$cache = [];
foreach ($keys as $key) {
$cache[$key] = $defaultCache; // if defaultCache It's the object,Deep copy is required
}
It is more powerful to use with array_map : combining array_map , array_column , array_combine and other functions can write very concise and flexible data processing logic.
array_fill_keys() is a very practical function in PHP, especially suitable for batch filling structures during the initialization phase. Whether you are doing cache initialization, data normalization, or configuration presets, using this function properly can make your code more neat and elegant.