php 2 array difference code example

Example 1: php find differences between two arrays

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Array
(
    [1] => blue
)

Example 2: multidimensional array difference in php

function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}
//----------------------
$changes = array();
if ($result= array_diff_assoc_recursive($new_value,$old_value)) {
		$new  = array();
		
		foreach ($result as $key => $value) {
			$new[$key] =  $value;
		}
		// indicate your UNIQUE ID you can use this when you want know which row you wanted to update in database 
		$new['ID'] = $new_value['ID'];
		$changes[] = $new	;
}

print_r($changes);

Tags:

Php Example