PHP

Compare Two Arrays to Find Added, Removed, and Common Elements

Efficiently determine the unique elements, common elements, and items present in one array but missing from another, providing a comprehensive comparison report.

<?php
function compare_arrays_detailed($array1, $array2) {
    $added = array_diff($array2, $array1); // Elements in array2 but not in array1
    $removed = array_diff($array1, $array2); // Elements in array1 but not in array2
    $common = array_intersect($array1, $array2); // Elements present in both arrays

    return [
        'added' => array_values($added), // Re-index for consistent output
        'removed' => array_values($removed),
        'common' => array_values($common)
    ];
}

$listA = ['apple', 'banana', 'orange', 'grape'];
$listB = ['banana', 'kiwi', 'apple', 'mango'];

echo "List A: ";
print_r($listA);
echo "List B: ";
print_r($listB);

$comparison_result = compare_arrays_detailed($listA, $listB);

echo "
Comparison Results:
";
echo "Added (in B, not in A):
";
print_r($comparison_result['added']);

echo "Removed (in A, not in B):
";
print_r($comparison_result['removed']);

echo "Common (in both A and B):
";
print_r($comparison_result['common']);

// Example with numeric arrays
$numbers1 = [1, 2, 3, 4, 5];
$numbers2 = [3, 4, 5, 6, 7];
$numeric_comparison = compare_arrays_detailed($numbers1, $numbers2);

echo "
Numeric Comparison Results:
";
print_r($numeric_comparison);
?>
How it works: This snippet provides a function `compare_arrays_detailed` that takes two arrays and returns a structured result showing elements that were 'added' (present in the second array but not the first), 'removed' (present in the first array but not the second), and 'common' (present in both). It leverages PHP's built-in `array_diff` and `array_intersect` functions for efficient comparison, re-indexing the results for clarity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs