PHP

Diff Two PHP Arrays of Associative Arrays by ID

Compare two arrays of associative arrays to identify items that have been added, removed, or modified, using a specified unique ID key.

function diffAssociativeArraysById(array $oldArray, array $newArray, string $idKey): array
{
    $oldMap = [];
    foreach ($oldArray as $item) {
        if (isset($item[$idKey])) {
            $oldMap[$item[$idKey]] = $item;
        }
    }

    $newMap = [];
    foreach ($newArray as $item) {
        if (isset($item[$idKey])) {
            $newMap[$item[$idKey]] = $item;
        }
    }

    $added = [];
    $modified = [];
    $removed = [];

    foreach ($newMap as $id => $newItem) {
        if (!isset($oldMap[$id])) {
            $added[] = $newItem;
        } elseif ($oldMap[$id] !== $newItem) {
            // Simple comparison, might need deeper check for complex objects
            $modified[] = $newItem;
        }
    }

    foreach ($oldMap as $id => $oldItem) {
        if (!isset($newMap[$id])) {
            $removed[] = $oldItem;
        }
    }

    return ['added' => $added, 'modified' => $modified, 'removed' => $removed];
}

$oldProducts = [
    ['id' => 1, 'name' => 'Laptop', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'price' => 25],
    ['id' => 3, 'name' => 'Keyboard', 'price' => 75],
];

$newProducts = [
    ['id' => 1, 'name' => 'Laptop Pro', 'price' => 1300], // Modified
    ['id' => 2, 'name' => 'Mouse', 'price' => 25],       // Unchanged
    ['id' => 4, 'name' => 'Monitor', 'price' => 300],    // Added
];

$diff = diffAssociativeArraysById($oldProducts, $newProducts, 'id');
/*
$diff will contain:
[
    'added' => [
        ['id' => 4, 'name' => 'Monitor', 'price' => 300]
    ],
    'modified' => [
        ['id' => 1, 'name' => 'Laptop Pro', 'price' => 1300]
    ],
    'removed' => [
        ['id' => 3, 'name' => 'Keyboard', 'price' => 75]
    ]
]
*/
How it works: This snippet provides a function `diffAssociativeArraysById` to compare two arrays of associative arrays, identifying which items have been added, modified, or removed based on a unique identifier key. It first maps both arrays by their ID for efficient lookup. Then, it iterates through the new items to find additions and modifications, and through the old items to find removals, returning a structured array of changes, which is crucial for data synchronization tasks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs