In actual development, especially when dealing with user configuration or multiple form settings, we often need to create a configuration array with a unified structure and similar content. In order to avoid repeated writing of code with the same structure, PHP's array_fill() function becomes a very practical tool.
This article will introduce how to create a configuration array template with a default structure using array_fill() and demonstrate it through a real case.
array_fill() is a built-in function in PHP that fills an array with specified values.
Function prototype:
array_fill(int $start_index, int $count, mixed $value): array
$start_index : The starting index of the array.
$count : The number of elements to be inserted.
$value : The default value for each element.
Suppose we are developing a user permission management system, and we need to generate a permission configuration array for each user role, each configuration item contains the following default structure:
[
'read' => false,
'write' => false,
'delete' => false,
'manage' => false,
'callback_url' => 'https://m66.net/api/callback'
]
If we need to initialize such a configuration for 5 different roles, using array_fill() will be very efficient.
<?php
// Define the default structure
$defaultPermission = [
'read' => false,
'write' => false,
'delete' => false,
'manage' => false,
'callback_url' => 'https://m66.net/api/callback'
];
// create 5 Array of role configuration
$roles = array_fill(0, 5, $defaultPermission);
// Optional:Assign a name to each role(For example admin、editor wait)
$roleNames = ['admin', 'editor', 'author', 'subscriber', 'guest'];
$config = array_combine($roleNames, $roles);
// Print the results to verify
print_r($config);
Array
(
[admin] => Array
(
[read] =>
[write] =>
[delete] =>
[manage] =>
[callback_url] => https://m66.net/api/callback
)
[editor] => Array
(
[read] =>
[write] =>
[delete] =>
[manage] =>
[callback_url] => https://m66.net/api/callback
)
...
)
Quotation problem : The same reference object is filled with array_fill() (especially important for arrays). If you modify the configuration of one of the roles in the future, the other roles will also be affected.
To avoid this problem, you can use array_map() with an anonymous function:
$roles = array_map(function () use ($defaultPermission) {
return $defaultPermission;
}, range(1, 5));
Structural consistency : This method is suitable for initialization scenarios where structural consistency is not yet determined.