PHP array_fill_keys: Create Arrays with Specific Keys

php array_fill_keys function

The PHP array_fill_keys function helps you to build an array where each key has the same value.

What is the array_fill_keys Function in PHP?

The array_fill_keys function creates an array with keys that you set in advance. Each key in the array holds the same value that you choose.

Here is the syntax:

array_fill_keys($keys, $value)
  • $keys: an array of keys that you want to use in the new array.
  • $value: the value that each key will hold.

The function returns a new array. If a key repeats, the last one replaces the earlier one.

You use this function when you have a set of keys and you want them to share the same value. This works for quick setup of default values or to prepare arrays for data that will come later.

Here is a quick example:

$keys = ['apple', 'banana', 'orange'];
$result = array_fill_keys($keys, 0);
print_r($result);

The output is:

Array
(
[apple] => 0
[banana] => 0
[orange] => 0
)

Here, the function makes an array where each fruit name holds the value 0. This is useful if you plan to count each fruit later.

Use the array_fill_keys with Arrays in PHP

Create an array with predefined keys and a single value:

$keys = [1, 2, 3, 4];
$array = array_fill_keys($keys, 'empty');
print_r($array);

This code creates a numeric-keyed array. Each number points to the word 'empty'.

Here is the output:

Array
(
[1] => empty
[2] => empty
[3] => empty
[4] => empty
)

Create an array with string keys and a set value:

$keys = ['north', 'south', 'east', 'west'];
$array = array_fill_keys($keys, 'unknown');
print_r($array);

This example builds a map direction array. Each direction starts with the same placeholder value 'unknown':

Array
(
[north] => unknown
[south] => unknown
[east] => unknown
[west] => unknown
)

Create a multi-dimensional array with php array_fill_keys:

$keys = ['user1', 'user2'];
$array = array_fill_keys($keys, ['status' => 'offline', 'score' => 0]);
print_r($array);

This creates an array where each user has a sub-array. The sub-array has a status and a score with initial values.

Here is the output:

Array
(
[user1] => Array
(
[status] => offline
[score] => 0
)

[user2] => Array
(
[status] => offline
[score] => 0
)

)

So, how to handle an empty keys array in php array_fill_keys?

If the $keys array is empty, the function returns an empty array.

$keys = [];
$array = array_fill_keys($keys, 'test');
var_dump($array);

The result is an empty array:

array(0) {
}

Use array_fill_keys with dynamic key lists from another array:

$source = ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'];
$keys = array_keys($source);
$array = array_fill_keys($keys, null);
print_r($array);

Here, the keys come from another array. The new array holds the same keys but each value is null. The output:

Array
(
[id] =>
[name] =>
[email] =>
)

The Difference Between array_fill and array_fill_keys

The array_fill creates an array with numeric keys that start from the index you set. While the array_fill_keys creates an array with specific keys from an array you provide.

Here is a table that shows you key differences:

Featurearray_fillarray_fill_keys
Key sourceAutomatic numbers begin at the given indexKeys come from provided array
Main usageFill a range of numeric keysFill custom keys
Example input keys0, 1, 2, 3‘a’, ‘b’, ‘c’ or custom numbers

Here is the use case:

  • Use array_fill when you need numeric keys in sequence.
  • Use array_fill_keys when you need custom keys like names or IDs.

Wrapping Up

In this article, you learned the use of array_fill_keys and how it differs from array_fill. You saw how to set values for many keys in one step. Here is a quick recap:

  • array_fill_keys builds arrays from a given set of keys.
  • You can use it for default values, templates, or structured data.
  • The function works with both numeric and string keys.
  • Empty key arrays result in empty arrays.

FAQs

How to use php array_fill_keys with an example?

$keys = array("a", "b", "c"); $result = array_fill_keys($keys, 0); print_r($result); 
This sets all keys "a", "b", and "c" to the value 0.

What is the difference between php array_fill and php array_fill_keys?

$keys = array("x", "y"); $result1 = array_fill(0, 2, "test"); $result2 = array_fill_keys($keys, "test"); print_r($result1); print_r($result2); 
array_fill uses numeric indexes starting at the given offset. array_fill_keys uses the keys you provide.

Can php array_fill_keys create arrays with numeric keys?

$keys = array(1, 2, 3); $result = array_fill_keys($keys, "value"); print_r($result); 
Yes. It supports numeric keys and string keys without any change in usage.

Similar Reads

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

PHP array_merge_recursive: Merge Arrays Deeply

PHP array_merge_recursive joins two or more arrays into one nested array and keeps all values with their keys. Syntax of…

How to Use PHP count() to Get Array Length

PHP developers may be need to determine the number of elements in an array. The count() function in PHP makes…

PHP strtolower Function: Convert Strings to Lowercase

Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…

PHP Named Arguments vs. Positional Arguments

The PHP named arguments are the names of the arguments through which the values are passed, allowing you to add…

PHP $_REQUEST: Learn How to Capture User Inputs

Today, we will discuss the most prominent and useful superglobal in PHP, $_REQUEST, to get user input. The $_REQUEST array lets you retrieve…

PHP MySQL CRUD: Understanding Database Operations

PHP and MySQL have become an inseparable pair for web developers. One handles the logic, while the other stores the…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

PHP Boolean: Assigning True or False to a Variable

You can assign the boolean data type to PHP variables or use it as a direct value. This enables you…

PHP array_shift: Remove the First Array Element with Examples

The array_shift function in PHP takes the first element from an array and returns it. It also moves all other…

Previous Article

HTML Attributes with Examples for Beginners

Next Article

JavaScript Class and Object Constructors with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.