PHP array_fill_keys() function
The array_fill_keys()
function in PHP is used to create an array where the keys are provided by the user, and all the keys are assigned the same value. This function is useful when you want to initialize an associative array with specific keys and a common default value for each of them.
Syntax:
Parameters:
- $keys: An array of keys that will be used to create the resulting array. These can be strings or integers, and duplicate keys are not allowed.
- $value: The value that will be assigned to each key in the resulting array. This can be of any type (integer, string, boolean, array, object, etc.).
Return Value:
- The function returns an associative array where the keys come from the
$keys
array, and each key is assigned the same$value
.
Example 1: Basic Usage
Output:
In this example, the keys "name"
, "age"
, and "email"
are assigned the value "unknown"
.
Example 2: Using Numeric Keys
You can also use numeric keys in the $keys
array.
Output:
In this case, the array has numeric keys with each key assigned the value 100
.
Example 3: Complex Values
You can assign complex data types (like arrays or objects) as the value.
Output:
In this example, each key ("user1"
, "user2"
, "user3"
) is assigned the same array as its value.
Example 4: Empty Keys Array
If the $keys
array is empty, the result will be an empty array.
Output:
Practical Usage:
array_fill_keys()
is useful for:- Initializing arrays with specific keys and a common default value.
- Setting up configuration arrays or form inputs where keys are predefined but the values need to be the same initially.
- Creating data structures with default values for further customization later on.
Comparison with array_fill()
:
array_fill()
fills an array starting from a specific index and applies values to indexed positions.array_fill_keys()
specifically works with associative arrays, where the keys are explicitly defined, and each key is assigned the same value.
Summary:
array_fill_keys($keys, $value)
creates an associative array using the provided keys, where all keys are assigned the same value.- This function is helpful for initializing arrays with predefined keys and default values, simplifying tasks like setting up configuration arrays, user profiles, or placeholder data.