Current Location: Home> Latest Articles> Resolution of return value when using empty array as keyname parameter

Resolution of return value when using empty array as keyname parameter

M66 2025-05-14

What is the return value when passing it to the array_fill_keys function using an empty array as a keyname parameter?

In PHP, the array_fill_keys function is a very useful tool that allows you to fill an array by specifying an array as the key name and a value. However, when you pass an empty array as the keyname parameter, what does the array_fill_keys function return? Let's make an in-depth analysis.

How to use array_fill_keys function

First, we need to understand the basic syntax of the array_fill_keys function:

 array_fill_keys(array $keys, mixed $value) : array
  • $keys : an array of key names to use.

  • $value : The value corresponding to each key.

This function returns a new array containing the key name from the $keys array and the value is the specified $value .

Pass an empty array as keyname parameter

When we pass an empty array as the $keys parameter, how will array_fill_keys be handled? Let's look at a simple example:

 <?php
$keys = [];
$value = "m66.net";
$result = array_fill_keys($keys, $value);

var_dump($result);
?>

Output result

 array(0) {
}

explain

When the key name parameter of the array_fill_keys function is an empty array, it returns an empty array. Although the value is specified (in this case "m66.net" ), the returned array is also empty because there is no key name.

In short, when you pass an empty array as a keyname parameter, array_fill_keys does not add any key-value pairs to the result array. This behavior can be understood as: without specifying a key name, there will be no elements that can be added to the array in the end.

Summarize

When using array_fill_keys , if the key name array is empty, the returned array will be an empty array. So, if you are expecting to get filled key-value pairs through an empty array, remember to make sure the key name array contains at least one element.