phparraysarray-difference

Find associative element changes between two flat arrays and return an array of affected keys with their before and after values


is there a function to compare 2 different associative arrays, and return changes?

For example

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "");
$age2 = array("Peter" => "38", "Ben" => "37", "Joe" => "43");

return

$return = array(
    "Peter" => "Changed from 35 to 38",
    "Joe" => "Changed from blank to 43"
);

Solution

  • As pointed out before, array_diff_assoc is your starting point. The rest is building your strings for each difference:

    function compareAge($age, $age2)
    {
        $return = array();
        foreach(array_keys(array_diff_assoc($age, $age2)) as $diffKey) {
            $from = empty($age[$diffKey]) ? 'blank' : $age[$diffKey];
            $to = empty($age2[$diffKey]) ? 'blank' : $age2[$diffKey];
            $return[$diffKey] = "Changed from {$from} to {$to}";
        }
        return $return;
    }
    

    working demo