Current Location: Home> Latest Articles> How to use array_fill_keys to handle empty arrays

How to use array_fill_keys to handle empty arrays

gitbox 2025-05-29

Why does empty array cause problems?

Suppose we write a function that expects to generate a default array of values ​​for subsequent use based on the user-provided key list:

 function initDefaults(array $keys, $defaultValue) {
    return array_fill_keys($keys, $defaultValue);
}

When $keys is empty, the function returns an empty array. If the code's subsequent logic does not specifically handle empty arrays, the following problems may be caused:

  • Traversal failed : The loop body is not executed, affecting the business logic;

  • Data missing : The expected default key-value pairs are not generated;

  • Program exception : For example, an undefined index error occurred when accessing array elements.


How to effectively avoid problems caused by empty arrays?

1. Pre-detect empty arrays

Before calling array_fill_keys , first determine whether the key array is empty:

 $keys = getKeysFromUser(); // May return an empty array

if (empty($keys)) {
    // According to business needs,Select a processing plan:
    // 1) Return an array of default keys
    // 2) Throw an exception prompt
    // 3) Directly return an empty array and be compatible in subsequent processing logic

    $keys = ['defaultKey']; // Use a default key here
}

$array = array_fill_keys($keys, 0);

This method can ensure that $array contains at least one element, avoiding errors during subsequent access.

2. Set the default key list

If business allows, a fixed set of default keys can be defined as an alternative:

 function safeFillKeys(array $keys, $defaultValue, array $defaultKeys = ['default']) {
    if (empty($keys)) {
        $keys = $defaultKeys;
    }
    return array_fill_keys($keys, $defaultValue);
}

When called:

 $result = safeFillKeys([], 0, ['key1', 'key2']);
print_r($result);

This way, even if an empty array is passed in, a reasonable default structure can be returned.

3. Use merge strategy

Combining the passed in key array and the default key array ensures that the final array is not empty:

 $keys = array_unique(array_merge($keys, ['fallbackKey']));
$array = array_fill_keys($keys, null);

array_unique guarantees that the key will not be repeated, array_merge appends the default key. This avoids the empty array situation.

4. Compatible with empty arrays in business logic

If you cannot control the call timing of array_fill_keys , you can add judgment when using the result:

 $array = array_fill_keys($keys, 0);

if (empty($array)) {
    // Special treatment,For example, initialize the default value
    $array = ['default' => 0];
}

// Continue to follow-up processing

Summarize

array_fill_keys is a concise and efficient function, but when the input key array is empty, the behavior of returning an empty array may cause hidden dangers to the program. Reasonable precautions include:

  • Determine whether the input array is empty in advance;

  • Set the default key value set;

  • Merge the passed key array with the default key array;

  • Compatible with empty array situations in business logic.

This can ensure the robustness and stability of the program and avoid logical vulnerabilities or errors caused by empty arrays.


 // Code Example:Safe use array_fill_keys
function safeArrayFillKeys(array $keys, $value, array $defaultKeys = ['default']) {
    if (empty($keys)) {
        $keys = $defaultKeys;
    }
    return array_fill_keys($keys, $value);
}

$keys = []; // Probably empty
$result = safeArrayFillKeys($keys, 0);
print_r($result);