$new_array = array_udiff ($array1, $array2,....,my_function());
my_function() : is the callback function to return integer less than , equal to or greater than zero after comparing the keys. function my_function($a, $b)
{
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
}
$first=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');
$second=array('One'=> 'First','2nd','Third');
$result=array_udiff($first,$second,"my_function");
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here.
Two -> Second
0 -> Fourth
Keys of the first index are retained. ( no re-indexing done here) . The element with value Third is not included in output as the value is matching with $second array.
We can use array_udiff() with multi-dimensional arrays to find differences between arrays based on specific keys:
More about strcmp() : Case sensitive string comparisonfunction compare_arrays($a, $b) {
return strcmp($a['name'], $b['name']);
}
$array1 = [
['name' => 'John', 'age' => 25],
['name' => 'Alice', 'age' => 30]
];
$array2 = [
['name' => 'John', 'age' => 27],
['name' => 'Bob', 'age' => 35]
];
$result = array_udiff($array1, $array2, 'compare_arrays');
print_r($result);
To compare arrays while ignoring case, use strcasecmp() in the callback:
function compare_ignore_case($a, $b) {
return strcasecmp($a, $b);
}
$array1 = ['First', 'Second', 'third'];
$array2 = ['first', 'Second', 'Third'];
$result = array_udiff($array1, $array2, 'compare_ignore_case');
print_r($result);
By comparing object properties, we can find unique objects across arrays:
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
function compare_objects($a, $b) {
return strcmp($a->name, $b->name);
}
$array1 = [new Person('John'), new Person('Alice')];
$array2 = [new Person('John'), new Person('Bob')];
$result = array_udiff($array1, $array2, 'compare_objects');
print_r($result);
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.