How to use array_udiff() Function In PHP
The array_udiff() function compares the values of two (or more) arrays using a user-defined comparison function and returns an array containing the values from the first array that are not present in any of the other arrays.
Example: The array_udiff() function uses a user-defined comparison function to compare the values of $arr1 and $arr2. The function compare compares the values and returns an array containing the values from $arr1 that are not present in $arr2.
<?php
// Declare two arrays
$arr1 = [1, 2, 3, 4, 5];
$arr2 = [4, 5, 6, 7, 8];
function compare($a, $b) {
return $a - $b;
}
$diff = array_udiff($arr1, $arr2, "compare");
print_r($diff);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 )
How to get the Difference Between Two Arrays in PHP?
Given two Arrays, the task is to get the difference between two arrays in PHP. To get the difference between two arrays, compare both arrays and retrieve values that are present in the first array but not in the second array.
Below are the approaches to get the difference between two arrays in PHP:
Table of Content
- Using array_diff() Function
- Using array_diff_assoc() Function
- Using array_udiff() Function
- Using array_diff_key() Function
Contact Us