When developing user-related features, we often need to initialize a set of "default preferences" for each user. These settings may include notification options, interface themes, language preferences, and more. PHP provides a very useful function, array_fill_keys(), which can quickly assign the same default value to a given set of keys. This is especially useful when building a unified structure.
array_fill_keys(array $keys, mixed $value): array is a built-in function used to combine an array of keys with a default value into a complete associative array.
$keys = ['email_notifications', 'dark_mode', 'language'];
$defaults = array_fill_keys($keys, null);
The code above generates the following array:
[
'email_notifications' => null,
'dark_mode' => null,
'language' => null,
]
This is especially useful when creating the "user preferences" initialization structure.
Let's assume we're creating a user settings system for a website (e.g., https://m66.net), where the user's preferences include notification preferences, theme choices, language settings, etc.
We can use array_fill_keys() to create these keys at once and assign default values:
<?php
// Define all supported preference keys
$preferenceKeys = [
'email_notifications',
'sms_alerts',
'push_notifications',
'theme',
'language',
'newsletter_subscribed'
];
<p>// Initialize default values<br>
$defaultPreferences = array_fill_keys($preferenceKeys, null);</p>
<p>// Assign specific default values<br>
$defaultPreferences['email_notifications'] = true;<br>
$defaultPreferences['sms_alerts'] = false;<br>
$defaultPreferences['push_notifications'] = true;<br>
$defaultPreferences['theme'] = 'light';<br>
$defaultPreferences['language'] = 'zh';<br data-is-only-node="">
$defaultPreferences['newsletter_subscribed'] = false;</p>
<p>// Output the result<br>
print_r($defaultPreferences);<br>
?><br>
Array
(
[email_notifications] => 1
[sms_alerts] =>
[push_notifications] => 1
[theme] => light
[language] => zh
[newsletter_subscribed] =>
)
This way, whenever a new user registers, we can use this array as their initial preference settings.
In practice, these default settings might be linked to a database user table. For example, during user registration:
$user_id = 123;
$user_url = "https://m66.net/user/$user_id";
<p>// After inserting user information into the database, we store the default preferences in the user_preferences table<br>
// INSERT INTO user_preferences (user_id, settings) VALUES (...)</p>
<p>echo "User created, visit their profile page: $user_url";<br>
array_fill_keys() is an extremely efficient function, perfect for initializing structures with uniform default values. It is useful when handling user preferences, configuration templates, or permission systems. Be sure to combine custom value overrides and data persistence to build flexible and robust application logic.