Current Location: Home> Latest Articles> Does the array_fill_keys function preserve the original key order?

Does the array_fill_keys function preserve the original key order?

M66 2025-06-30

In PHP, array_fill_keys is a very useful array operation function that fills an array with specified keys and values. In actual development, understanding how it works and whether it preserves the original order of the keys is very important. This article will explore, through examples, whether the array_fill_keys function maintains the original key order.

Function Overview

array_fill_keys fills an array with a specified value, and the keys are taken from a given array. The basic syntax is as follows:

array_fill_keys(array $keys, mixed $value): array
  • $keys: The keys used to fill the array, which can be an indexed array.

  • $value: The value assigned to each key.

Example Code

Let's look at a simple example to understand the basic usage of the array_fill_keys function:

<?php
$keys = ['a', 'b', 'c', 'd'];
$value = 100;
<p>$result = array_fill_keys($keys, $value);<br>
print_r($result);<br>
?><br>

Output:

Array
(
    [a] => 100
    [b] => 100
    [c] => 100
    [d] => 100
)

As we can see from this example, the array_fill_keys function creates a new array using the specified keys ['a', 'b', 'c', 'd'] and assigns the value 100 to each key.

Does it preserve the original key order?

In PHP, the array_fill_keys function preserves the order of the keys in the input array. This means that the keys in the returned array will match the order of the original keys.

In PHP’s implementation, arrays are ordered (for associative arrays). Therefore, when you provide an ordered array of keys, array_fill_keys will fill the array following that same order.

Example: Does the key order remain intact?

<?php
$keys = ['apple', 'banana', 'cherry'];
$value = 'fruit';
<p>$result = array_fill_keys($keys, $value);<br>
print_r($result);<br>
?><br>

Output:

Array
(
    [apple] => fruit
    [banana] => fruit
    [cherry] => fruit
)

As shown above, the returned array maintains the original key order, with the sequence of 'apple', 'banana', and 'cherry' unchanged.

Another Example: What if the key order is changed?

If the key order is changed, array_fill_keys will fill the array according to the new order:

<?php
$keys = ['dog', 'cat', 'bird'];
$value = 'animal';
<p>$result = array_fill_keys($keys, $value);<br>
print_r($result);<br>
?><br>

Output:

Array
(
    [dog] => animal
    [cat] => animal
    [bird] => animal
)

Summary

array_fill_keys preserves the original key order of the input array and fills the array following that order. If you provide an ordered key array, the returned result will follow the same sequence.

Code Related to URLs

Suppose you have the following URL-related code snippet, where we need to replace the domain name in the URL with m66.net.

<?php
$url = 'http://m66.net/api/data';
$response = file_get_contents($url);
echo $response;
?>