When processing data, we often encounter situations where we need to batch reset certain field values in the array to the initial value. This requirement is especially common, for example, when resetting user information, initializing configuration, or clearing form fields. The array_fill_keys() function provided by PHP can help us achieve this goal efficiently.
array_fill_keys() is an array function provided by PHP. Its function is to create an array using the specified key name and set the same value for each key . The function prototype is as follows:
array array_fill_keys(array $keys, mixed $value)
$keys : an array containing array keys.
$value : The value to be filled to each key.
Suppose we have an array of user information, as follows:
$user = [
'name' => 'Alice',
'email' => 'alice@m66.net',
'phone' => '123456789',
'address' => '123 Street'
];
Now we want to reset the values of the three fields name , email and phone to an empty string, we can do this:
$fieldsToReset = ['name', 'email', 'phone'];
$resetValues = array_fill_keys($fieldsToReset, '');
$user = array_merge($user, $resetValues);
print_r($user);
Array
(
[name] =>
[email] =>
[phone] =>
[address] => 123 Street
)
As you can see, array_fill_keys() quickly generates a new array where the values of the specified fields are set to empty, and then we use array_merge() to combine it with the original number to achieve the purpose of batch reset.
Another common use is to initialize a set of configuration items. For example, you might need to initialize the settings for a module:
$settingsKeys = ['theme', 'language', 'timezone', 'notifications'];
$defaultSettings = array_fill_keys($settingsKeys, null);
print_r($defaultSettings);
Array
(
[theme] =>
[language] =>
[timezone] =>
[notifications] =>
)
This ensures that each setting item has a default value, avoiding errors when accessing undefined indexes.
Using array_fill_keys() can greatly simplify our batch reset or initialization of data fields in PHP. Combined with array_merge() , it can also be elegantly fused with the original array, which is a very practical technique for processing array data.
In daily development, when you encounter a need to set a set of fields to a certain value uniformly, don't forget to try array_fill_keys() - simple, efficient and elegant.