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

PHP $_FILES: How to Upload Files in PHP

The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…

PHP Predefined Constants Explained Simply

PHP has a number of predefined constants that give you some information about the language and its environment. You can…

PHP Prepared Statements in MySQL: Preventing SQL Injection

MySQL Prepared Statements in PHP are an important tool for ensuring security and optimization. They safeguard against SQL injection attacks,…

PHP mb_substr Function: How it Works with Examples

You may need to get part of a text when you work with text in PHP. The mb_substr gives you…

PHP array_count_values: How it Works with Examples

Developers use the array_count_values function in PHP to find how many times each value appears in an array. What is…

PHP Math: Essential Functions with Examples

PHP math may sound like a pretty simple thing, but I assure you it's a set of tools that will…

Polymorphism in PHP: How It Works with Examples

PHP 5 added support for classes and interfaces. This made object-oriented code possible with one feature being polymorphism. That means…

IF-Else: Executes the IF-Else Statement in PHP

Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

PHP array_any: How it Works with Arrays with Examples

PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

PHP filter_input: How to Validate Input Securely

User input can be risky. Hackers exploit weak validation to inject malicious data. PHP filter_input() helps you sanitize and validate…

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.