How to extract specific array keys and values to another array?

How to extract specific array keys and values to another array?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Transforming Nested Arrays in PHP: From List to Map

When working with structured data in PHP, you frequently encounter nested arrays where every sub-array shares a common schema. Consider a scenario where you have a collection of items, each containing metadata like id, desc, type, and title. Often, the full object is only needed for specific operations, but you require a flattened representation that maps one field directly to another.

In this case, the goal is to take an array of associative arrays and construct a new array where the keys are the values from the id field and the values come from the type field. The resulting structure should look like ['post_1' => 'type1', 'post_2' => 'type2'].

While you might search for a dedicated function to perform this extraction, PHP's standard library does not provide a specific "extract key A to key B" utility. Instead, the most idiomatic solution relies on array_map, which applies a callback function to every element in the source array. This approach is explicit, readable, and leverages PHP's core iteration capabilities without requiring external dependencies.

Here is how you can implement this transformation:

$data = [
    ['id' => 'post_1', 'desc' => 'Description 1', 'type' => 'type1', 'title' => 'Title'],
    ['id' => 'post_2', 'desc' => 'Description 2', 'type' => 'type2', 'title' => 'Title']
];

$result = array_map(function ($item) {
    return $item['id'] => $item['type'];
}, $data);

Wait, that syntax isn't valid PHP. You cannot construct an array with the => operator inside a return statement like that in older versions of PHP (5.4 and below). In modern PHP (5.4+), you can use the short array syntax [key => value], but array_map requires a callback that returns a single value unless using arrow functions or specific syntax adjustments available in 8.0+.

A more robust and version-agnostic approach uses the traditional array construction inside the closure:

$result = array_map(function ($item) {
    $newKey = $item['id'];
    $newValue = $item['type'];
    
    // Using the long syntax to ensure compatibility across PHP versions
    return [$newKey => $newValue];
}, $data);

However, this creates an array of arrays where each element is a single-key map. To get the associative array directly as your target structure, you need to initialize an empty array and use array_combine logic or simply build it manually if performance isn't critical for small datasets. Actually, there is a cleaner way using array_map with short array syntax if you are on PHP 8.0+, but for broader compatibility, let's look at the most straightforward method:

$result = [];
foreach ($data as $item) {
    $result[$item['id']] = $item['type'];
}

This loop is arguably the clearest and most performant solution for this specific task. It avoids the overhead of creating intermediate arrays and allows you to handle edge cases easily within the loop body.

Handling Edge Cases and Data Integrity

While the simple loop works perfectly for clean data, real-world inputs often contain inconsistencies. You might encounter missing keys or null values. If $item['id'] is missing, attempting to use it as a key will throw a notice in strict environments or default to an empty string if not handled. Similarly, duplicate id values will result in the last item overwriting previous ones in the new array.

If data validation is part of your workflow, you should check for the existence of keys before accessing them:

foreach ($data as $item) {
    if (isset($item['id'], $item['type'])) {
        $result[$item['id']] = $item['type'];
    }
}

This ensures that malformed entries are skipped rather than causing runtime errors or data loss.

When to Use array_map vs foreach

You might wonder why we didn't stick with array_map. In PHP, array_map is primarily designed to apply a function to elements and return a new array of the same size (or transformed values). Using it to build a dictionary structure requires returning an array from the callback, which adds a layer of indirection. If you simply want to transform keys based on existing values, a foreach loop is often more readable and slightly faster because it avoids creating an intermediate value for each iteration if you are building a new associative array directly.

For larger datasets where performance is critical, this manual construction is efficient enough without needing complex iterator implementations. If you need to extract multiple keys or perform complex logic on the values, array_map becomes more attractive due to its functional nature and ability to chain with other higher-order functions.

Conclusion

There is no single magic function in PHP that automatically maps one specific key to another across an entire array without a loop or callback. The solution lies in understanding how PHP's iteration tools work together. Whether you choose a simple foreach loop for clarity or array_map for functional style, the core logic remains the same: iterate over the source, extract the required fields, and assign them to the new structure based on your desired key mapping.

Our network