PHP

Compare Two Associative Arrays and Find Key Differences in PHP

Discover how to identify keys present in one associative array but missing from another, essential for managing configurations, permissions, or data synchronization.

<?php
$array1 = [
    'name' => 'Product A',
    'price' => 100,
    'stock' => 50,
    'category' => 'Electronics'
];

$array2 = [
    'name' => 'Product A',
    'price' => 100,
    'description' => 'A great gadget.',
    'weight' => '1kg'
];

// Find keys in $array1 that are not in $array2
$keysOnlyInArray1 = array_diff_key($array1, $array2);
// $keysOnlyInArray1 will be ['stock' => 50, 'category' => 'Electronics']
print_r($keysOnlyInArray1);

// Find keys in $array2 that are not in $array1
$keysOnlyInArray2 = array_diff_key($array2, $array1);
// $keysOnlyInArray2 will be ['description' => 'A great gadget.', 'weight' => '1kg']
print_r($keysOnlyInArray2);

// Find common keys (intersection of keys)
$commonKeys = array_intersect_key($array1, $array2);
// $commonKeys will be ['name' => 'Product A', 'price' => 100]
print_r($commonKeys);
?>
How it works: This snippet uses `array_diff_key()` to compare two associative arrays and return the key-value pairs from the first array whose keys are not present in the second array. It's useful for identifying missing or extra configuration parameters, comparing database record changes based on column presence, or synchronizing data structures by their keys. Additionally, `array_intersect_key()` is shown for finding keys that are common to both arrays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs