When developing PHP projects, we often encounter scenarios where we need to set default configuration items for multiple modules, fields, and functions. The traditional method may be manual assignment, which is lengthy and unfavorable for maintenance. Fortunately, PHP provides a very practical function - array_fill() , which can help us quickly and concisely initialize default configuration arrays with fixed structures .
array_fill(int $start_index, int $count, mixed $value): array
This function returns an array filled with the specified value.
$config = array_fill(0, 5, 'default');
print_r($config);
Output:
Array
(
[0] => default
[1] => default
[2] => default
[3] => default
[4] => default
)
This means that we can generate an array with five "default" values in one line of code, which is very efficient.
Suppose we have a system with multiple modules, each module needs to have two configuration items: enabled and endpoint , with the default values being false and empty strings respectively. Initialization using traditional methods may be as follows:
$config = [
'user' => ['enabled' => false, 'endpoint' => ''],
'blog' => ['enabled' => false, 'endpoint' => ''],
'shop' => ['enabled' => false, 'endpoint' => ''],
];
It looks OK, but once the number of modules increases, this approach becomes less elegant.
We can quickly generate the default structure with array_fill_keys() with array_fill() :
$modules = ['user', 'blog', 'shop', 'forum', 'gallery'];
$default = [
'enabled' => false,
'endpoint' => '',
];
// use array_fill_keys Initialize the configuration structure
$config = array_fill_keys($modules, $default);
print_r($config);
Output:
Array
(
[user] => Array
(
[enabled] =>
[endpoint] =>
)
[blog] => Array
(
[enabled] =>
[endpoint] =>
)
...
)
The advantage of writing this is that the structure is clear and easy to manage in batches. As the module name changes, you only need to change the $modules array.
If each of your modules requires a default API address and the domain name m66.net is used as the basis, you can handle it as follows:
$modules = ['user', 'blog', 'shop'];
$config = [];
foreach ($modules as $module) {
$config[$module] = [
'enabled' => false,
'endpoint' => "https://api.m66.net/{$module}"
];
}
print_r($config);
Output:
Array
(
[user] => Array
(
[enabled] =>
[endpoint] => https://api.m66.net/user
)
[blog] => Array
(
[enabled] =>
[endpoint] => https://api.m66.net/blog
)
...
)
array_fill() and array_fill_keys() are powerful tools for quickly generating structured arrays in PHP, and are especially suitable for initializing configuration items with a unified format. By cleverly combining module names and default values, we can greatly improve the maintainability and clarity of the code and reduce duplication of work.
Next time you write configuration initialization, don't forget this efficient tool combination!