Current Location: Home> Latest Articles> array_fill_keys + array_map: Quickly construct an associative array

array_fill_keys + array_map: Quickly construct an associative array

M66 2025-06-06

In PHP, arrays are very important data structures, and associative arrays are a commonly used form in daily development. Many times, we need to quickly construct associative arrays according to certain rules. PHP's two functions array_fill_keys() and array_map() can be used very cleverly to help us complete this task efficiently.

1. Introduction to array_fill_keys()

array_fill_keys() is a very convenient PHP function that generates an associative array filled with the same value based on the specified key. Its definition is as follows:

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

  • $value : Fill in the corresponding value of each key.

For example, use array_fill_keys() to create an array containing multiple keys and fill in the same value:

 $keys = ['a', 'b', 'c'];
$value = 0;

$result = array_fill_keys($keys, $value);
print_r($result);

Output result:

 Array
(
    [a] => 0
    [b] => 0
    [c] => 0
)

2. Introduction to array_map()

array_map() is another very commonly used PHP function that applies a callback function to each element in an array and returns a new array. Its definition is as follows:

 array array_map ( callable $callback , array $array1 [, array $array2 [, array $... ]] )
  • $callback : The callback function that performs operations on each element in the array.

  • $array1 : Enter an array, there can be multiple array parameters, and the callback function will act on these arrays in turn.

For example, we can process each value of an array:

 $numbers = [1, 2, 3, 4];
$squared = array_map(function($num) {
    return $num * $num;
}, $numbers);

print_r($squared);

Output result:

 Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
)

3. Use array_fill_keys() and array_map() in combination

Suppose we have an array containing a set of key names and want to generate one value for each key, which comes from another array, and that some processing is required for these values. By combining array_fill_keys() and array_map() , we can accomplish this task very efficiently.

For example, suppose we have an array of multiple product names, we want to set an initial price for each product, and these prices need to be adjusted according to certain rules.

 $keys = ['product1', 'product2', 'product3'];
$prices = [10, 20, 30];

// usearray_fill_keysGenerate an initial price for each item
$initialPrices = array_fill_keys($keys, null);

// usearray_mapAdjust prices
$adjustedPrices = array_map(function($price) {
    return $price * 1.2;  // For example, we add20%Price
}, $prices);

// 将调整后Price与商品键关联
$finalPrices = array_combine($keys, $adjustedPrices);

print_r($finalPrices);

Output result:

 Array
(
    [product1] => 12
    [product2] => 24
    [product3] => 36
)

4. Use scenarios

This combined method is especially suitable for scenarios where large amounts of data are required to operate in batches. for example:

  • Get the product name from the database, generate the price and apply the discount.

  • Generate configuration arrays and process them according to settings entered by a set of user.

  • Map multiple data sets and return an associative array with the same key name.

The advantages of this approach are:

  1. Concise : Avoid duplicate code logic.

  2. Flexible : array_map() can flexibly adjust data through custom callback functions.

  3. Efficiency : The combination of two functions can effectively reduce the amount of code and improve development efficiency.

5. Things to note

  • All values ​​in the array generated by array_fill_keys() will be initialized to the same value. If we need to generate values ​​according to different rules, we can consider using them in combination with array_map() .

  • The array_combine() function is used to combine two arrays into an associative array, which is used to associate the adjusted price with the product name.

6. Summary

By combining array_fill_keys() and array_map() , we are able to handle the construction and modification of associative arrays very concise and efficiently. Whether it is data processing or batch generation of arrays of specific structures, the combination of these two functions can greatly simplify the code.