Sometimes you need to create an associative array with specific keys and assign the same initial value to every entry. For example, you might want to initialize form fields, set default task statuses, or prepare product quantities.
PHP provides the array_fill_keys() function to create these arrays without manually assigning each key.
In this guide, you'll learn how the function works, how it handles duplicate and numeric keys, and how to use it in practical applications.
What Is array_fill_keys() in PHP?
The array_fill_keys() function creates a new array using a list of predefined keys. Every key receives the same value.
Its syntax is:
array_fill_keys(
array $keys,
mixed $value
): array
The function accepts two parameters:
$keys— An array containing the keys for the new array.$value— The initial value assigned to every key.
It returns a new associative array without modifying the original keys array.
The function has been available since PHP 5.2 and is supported in PHP 8.
Example 1: Creating an Array with Default Values
Let's create an array of form fields, each initialized with the value "Not provided".
<?php
$fields = ["name", "email", "phone"];
$formData = array_fill_keys(
$fields,
"Not provided"
);
print_r($formData);
Output:
Array
(
[name] => Not provided
[email] => Not provided
[phone] => Not provided
)
Each element from $fields becomes a key in the new array.
You can update individual values afterward:
$formData["name"] = "Alex";
echo $formData["name"];
Output:
Alex
The other fields retain their original default values.
Example 2: Using Numeric Keys
The function also supports integer keys.
For example, let's initialize stock quantities for three products.
<?php
$productIds = [101, 102, 103];
$stock = array_fill_keys($productIds, 0);
print_r($stock);
Output:
Array
(
[101] => 0
[102] => 0
[103] => 0
)
Notice that the product IDs become the keys. PHP doesn't automatically replace them with sequential indexes.
This makes array_fill_keys() useful for initializing lookup arrays based on existing identifiers.
What Happens with Duplicate Keys?
PHP arrays cannot contain the same key more than once.
If the input contains duplicate keys, the resulting array contains only one entry for each unique key.
<?php
$fields = [
"name",
"email",
"name"
];
$result = array_fill_keys($fields, null);
echo count($result);
Output:
2
The result contains only name and email.
Also remember that PHP may convert certain numeric string keys into integers. For example, "123" becomes the integer key 123, while a string such as "00123" remains a string.
When the exact key format matters, validate your input before creating the array.
Practical Example: Initializing Task Statuses
Imagine you're building a task management application. You have several tasks identified by unique IDs, and every task should initially have a status of "Pending".
Instead of manually creating an associative array, you can initialize all statuses with array_fill_keys().
Create a file named task-statuses.php:
<?php
declare(strict_types=1);
// List of task IDs.
$taskIds = [
"TASK-101",
"TASK-102",
"TASK-103",
"TASK-104"
];
// Initialize all tasks as pending.
$statuses = array_fill_keys(
$taskIds,
"Pending"
);
// Update completed tasks.
$statuses["TASK-101"] = "Completed";
$statuses["TASK-103"] = "Completed";
// Display task statuses.
echo "<h2>Task Statuses</h2>";
echo "<ul>";
foreach ($statuses as $taskId => $status) {
$message = $taskId . ": " . $status;
echo "<li>" . htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
) . "</li>";
}
echo "</ul>";
Browser output:
Task Statuses
TASK-101: Completed
TASK-102: Pending
TASK-103: Completed
TASK-104: Pending
The function creates a consistent starting structure, while individual task statuses can be updated independently.
This technique also works for permission flags, feature settings, inventory quantities, and other collections that need predefined keys.
Handling Empty Arrays and Other Value Types
If the keys array is empty, the function returns an empty array:
<?php
$result = array_fill_keys([], false);
var_dump($result);
Output:
array(0) {
}
The second parameter accepts different PHP data types, including strings, integers, booleans, null, and arrays.
However, if you use an object as the default value, every entry refers to the same object instance. Modifying that object through one key affects the object visible through the other keys.
For independent objects, create a separate instance for each entry instead.
array_fill_keys() vs array_fill() vs array_combine()
These functions all create arrays, but each serves a different purpose.
| Function | Purpose |
|---|---|
array_fill_keys() |
Creates an array with predefined keys and one shared default value. |
array_fill() |
Creates a specified number of elements using consecutive numeric keys. |
array_combine() |
Creates an array using one list for keys and another for corresponding values. |
Use array_fill_keys() when you already know which keys you need and want every entry to start with the same value.
Key Takeaways
array_fill_keys()creates an array using predefined keys.- Every key receives the same initial value.
- Both string and integer keys are supported.
- Duplicate keys produce only one entry per unique key.
- An empty keys array produces an empty result.
- The function returns a new array without modifying the original.
The array_fill_keys() function is a convenient way to initialize associative arrays with consistent default values. It keeps your code short and readable when preparing structured data for later processing.
For additional details, see the official PHP array_fill_keys() documentation.