How to create an array with default values using the array_fill_keys function in PHP?
In PHP, the array_fill_keys() function is a very useful function that can help us create an associative array with default values. This function is especially suitable for scenarios where arrays need to be created based on certain keys, while ensuring that each key has the same default value.
The syntax of the array_fill_keys() function is as follows:
array array_fill_keys(array $keys, mixed $value)
$keys : an array containing keys.
$value : The default value used to fill the array.
This function creates a new associative array based on each key in the $keys array and gives each key the same default value $value .
Here is an example showing how to create an array with default values using the array_fill_keys() function:
<?php
// Define key array
$keys = ['apple', 'banana', 'cherry'];
// Set default values
$default_value = 'fruit';
// use array_fill_keys Create an array with default values
$array = array_fill_keys($keys, $default_value);
// Output result
print_r($array);
?>
Array
(
[apple] => fruit
[banana] => fruit
[cherry] => fruit
)
In this example, we create an array $keys containing the fruit names and then use array_fill_keys() to specify the default value 'fruit' for each fruit name. The result is a new associative array, with each fruit name corresponding to the value 'fruit' .
If you want to use these keys with URLs (for example, generate an array of links with default values), you can refer to the following example:
<?php
// Define some page paths
$pages = ['home', 'about', 'contact'];
// Create a link array with default values,The default value is m66.net domain name
$urls = array_fill_keys($pages, 'https://m66.net');
// Output result
print_r($urls);
?>
Array
(
[home] => https://m66.net
[about] => https://m66.net
[contact] => https://m66.net
)
In this example, we create an associative array for three pages ( home , about and contact ), and the corresponding link for each page points to https://m66.net by default.
The array_fill_keys() function is very useful in many real projects, especially when you need to initialize an array with multiple keys and set a unified default value for these keys. Common scenarios include:
Initialize the configuration array : Set default values for configuration items.
Generate link array : Generate URLs with the same domain name for each page.
Create default form data : When processing a form, create a default array of data for form fields.
With the array_fill_keys() function, you can easily create an array containing specific keys and default values. Whether it is in configuration settings, generating URLs, or other scenarios that require default values, array_fill_keys() can help you. Hope this article helps you understand how to use this function!