Search code examples
phparray-difference

comparing two arrays and return difference of arrays


My old array data:

[Job] => Array
        (
            [id] => 2
            [job_state_id] => 14
            [assigned_to_id] => 
            [patient_id] => 2
            [prescription] => main
            [case_type_id] => 1
            [upper_midline_id] => 1
            [upper_midline_value] => 0
            [lower_midline_id] => 1
            [lower_midline_value] => 0
            [treat_arches] => 2
            [upper_midline_type_id] => 2
            [lower_midline_type_id] => 2
            [overjet] => 2
            [overbite] => 2
            [arch_form] => 2
            [canine_relationship] => 2
            [molar_relationship] => 1
            [posterior_crossbite] => 1
            [procline] => 2
            [expand] => 2
            [distalize] => 0
            [ipr] => 0
            [close_all_spaces] => 2
            [other_instructions] => other

and my new array data:

[Job] => Array
        (
            [id] => 2
            [job_state_id] => 14
            [assigned_to_id] => 
            [patient_id] => 2
            [prescription] => main complain
            [case_type_id] => 1
            [upper_midline_id] => 1
            [upper_midline_value] => 0
            [lower_midline_id] => 1
            [lower_midline_value] => 0
            [treat_arches] => 2
            [upper_midline_type_id] => 2
            [lower_midline_type_id] => 2
            [overjet] => 2
            [overbite] => 2
            [arch_form] => 2
            [canine_relationship] => 2
            [molar_relationship] => 1
            [posterior_crossbite] => 1
            [procline] => 2
            [expand] => 2
            [distalize] => 0
            [ipr] => 1
            [close_all_spaces] => 2
            [other_instructions] => other instrucations

you can see some values are change. I need to compare the $new array data against the $old data array and catch only the change made on the value. i have use this code:

$difference = array_diff($oldJobData, $newJobData);

difference variable return $oldJobData i want only difference not whole array i have use following code also but can't get desire result.

          $new2 = array();
            foreach ($newJobData as $key => $new_val) {
                if (isset($oldJobData[$key])) { // belongs to old array?
                    if ($oldJobData[$key] != $new_val) // has changed?
                        $new2[$key] = $newJobData[$key]; // catch it
                }
            }

Solution

  • You have an associative array and as such must use array_diff_assoc:

    $changes = array_diff_assoc($new, $old);