Current Location: Home> Latest Articles> Common ways to cooperate with array_fill_keys and array_keys

Common ways to cooperate with array_fill_keys and array_keys

M66 2025-05-17

In PHP, arrays are very common and important data structures. During the programming process, we often need to search, filter, modify and other operations of arrays. PHP provides a rich array processing function, where array_fill_keys and array_keys are two powerful functions. Cleverly combining these two functions can help us optimize array operations and improve code efficiency.

Introduction to array_fill_keys and array_keys

  • array_keys()
    array_keys() is used to return an array of all key names in the array. This function is usually very useful when we need to get the values ​​of certain keys in the array.

     $array = ['a' => 1, 'b' => 2, 'c' => 3];
    $keys = array_keys($array); // return ['a', 'b', 'c']
    
  • array_fill_keys()
    array_fill_keys() is used to fill the specified key name with a specific value. This function will generate a new array based on the passed key names array, and fill all the values ​​corresponding to these key names with the specified values.

     $keys = ['a', 'b', 'c'];
    $filledArray = array_fill_keys($keys, 0); // return ['a' => 0, 'b' => 0, 'c' => 0]
    

Optimization techniques for using array_fill_keys and array_keys in conjunction with array_keys

The combination of these two functions can help us efficiently handle some common array operations, such as determining whether an array contains certain key names and assigning default values ​​to these key names. The following are several common application scenarios.

1. Set default values ​​for missing keys in array

Suppose we have an array containing certain key names, but we are not sure if certain key names are missing in the array. If these key names are missing, we want to set default values ​​for them. At this time, it can be implemented in combination with array_fill_keys and array_keys .

Sample code:

 $array = ['a' => 1, 'b' => 2];

// Define the key name to be checked
$requiredKeys = ['a', 'b', 'c', 'd'];

// Get the existing key name in the array
$existingKeys = array_keys($array);

// Find the missing key name
$missingKeys = array_diff($requiredKeys, $existingKeys);

// use array_fill_keys Set default values ​​for missing key names
$defaultValues = array_fill_keys($missingKeys, 0);

// Merge the original array with missing key-value pairs
$finalArray = array_merge($array, $defaultValues);

print_r($finalArray);

Output:

 Array
(
    [a] => 1
    [b] => 2
    [c] => 0
    [d] => 0
)

In this example, we use array_keys to get the existing key names in the array, use array_diff to find the missing key names, then use array_fill_keys to fill the default value 0 for these missing key names, and finally merge the original array and the new key-value pair through array_merge .

2. Dynamically add default values ​​for multiple keys

Sometimes we need to dynamically add multiple key default values ​​to the array. Extracting the existing key name through array_keys and filling the default value with array_fill_keys can make the code more concise and efficient.

Sample code:

 $existingArray = ['x' => 1, 'y' => 2];

// Define a new key name
$newKeys = ['a', 'b', 'c'];

// use array_fill_keys Fill in the default value for the new key name
$newValues = array_fill_keys($newKeys, 0);

// Merge existing arrays and new key-value pairs
$finalArray = array_merge($existingArray, $newValues);

print_r($finalArray);

Output:

 Array
(
    [x] => 1
    [y] => 2
    [a] => 0
    [b] => 0
    [c] => 0
)

Here, we first fill the default value 0 of the new key name through array_fill_keys , and then combine it with the original number to get the final result.

3. Processing arrays with URLs

In some cases, we may need to process arrays containing URLs, and the domain names in these URLs may need to be uniformly replaced. Suppose we need to replace all URL domain names in the array with m66.net , we can use array_map to process it with str_replace .

Sample code:

 $urls = [
    'https://www.example.com/page1',
    'https://www.example.com/page2',
    'https://m66.net/page3'
];

// Replace all URL Domain name in
$updatedUrls = array_map(function ($url) {
    return preg_replace('/https?:\/\/(www\.)?[^\/]+/', 'https://m66.net', $url);
}, $urls);

print_r($updatedUrls);

Output:

 Array
(
    [0] => https://m66.net/page1
    [1] => https://m66.net/page2
    [2] => https://m66.net/page3
)

By replacing the domain name in the URL with regular expressions, we can easily replace the domain name of all URLs with m66.net , thus completing the batch replacement operation.

Summarize

By cleverly combining array_fill_keys and array_keys , we can optimize array operations in PHP, especially when dealing with array key names. Whether it is setting default values ​​for missing key names, adding new key values ​​dynamically, or batching URL arrays, the combination of these functions can help us write more efficient and concise code. In actual development, the rational use of these array functions can greatly improve the readability and execution efficiency of the code.