PHP
Create a Fast Lookup Map from an Array of Associative Arrays in PHP
Efficiently transform an array of associative arrays into a key-value lookup map, enabling rapid access to specific items using a chosen identifier as the key.
<?php
$users = [
['id' => 101, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 102, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 103, 'name' => 'Charlie', 'email' => '[email protected]']
];
// Create a map where 'id' is the key
$usersById = array_reduce($users, function($carry, $item) {
$carry[$item['id']] = $item;
return $carry;
}, []);
// Access an item directly by ID
// $usersById[102] will be ['id' => 102, 'name' => 'Bob', 'email' => '[email protected]']
print_r($usersById[102]);
// Example with a different key (email)
$usersByEmail = array_reduce($users, function($carry, $item) {
$carry[$item['email']] = $item;
return $carry;
}, []);
print_r($usersByEmail['[email protected]']);
?>
How it works: This snippet demonstrates how to transform an array of associative arrays into a new associative array (a lookup map) using `array_reduce`. It iterates through the original array, using a specified key from each inner array (e.g., 'id' or 'email') as the key for the new map, and the entire inner array as its value. This allows for O(1) average-case time complexity lookup of items, significantly faster than iterating through the original array when you need to access items by a unique identifier.