array_diff
Сравнивает array1 с одним или несколькими другими массивами и возвращает значения из array1 , которые отсутствуют во всех других массивах.
Список параметров
Массив, с которым идет сравнение
Дополнительные массивы, с которыми осуществляется сравнение
Возвращаемые значения
Возвращает array , содержащий элементы array1 , отсутствующие в любом из всех остальных массивах.
Примеры
Пример #1 Пример использования array_diff()
$array1 = array( «a» => «green» , «red» , «blue» , «red» );
$array2 = array( «b» => «green» , «yellow» , «red» );
$result = array_diff ( $array1 , $array2 );
?php
Множественные совпадения в $array1 обрабатываются как одно. Результат будет следующим :
Примечания
Замечание:
Два элемента считаются одинаковыми тогда и только тогда, если (string) $elem1 === (string) $elem2. Другими словами, когда их строковое представление идентично.
Замечание:
Обратите внимание, что эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff($array1[0], $array2[0]);.
Смотрите также
- array_diff_assoc() — Вычисляет расхождение массивов с дополнительной проверкой индекса
- array_intersect() — Вычисляет схождение массивов
- array_intersect_assoc() — Вычисляет схождение массивов с дополнительной проверкой индекса
array_udiff
Computes the difference of arrays by using a callback function for data comparison. This is unlike array_diff() which uses an internal function for comparing the data.
Parameters
Arrays to compare against.
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Returning non-integer values from the comparison function, such as float , will result in an internal cast to int of the callback’s return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0 , which will compare such values as equal.
Return Values
Returns an array containing all the values of array that are not present in any of the other arguments.
Examples
Example #1 array_udiff() example using stdClass Objects
// Arrays to compare
$array1 = array(new stdClass , new stdClass ,
new stdClass , new stdClass ,
);
?php
$array2 = array(
new stdClass , new stdClass ,
);
// Set some properties for each object
$array1 [ 0 ]-> width = 11 ; $array1 [ 0 ]-> height = 3 ;
$array1 [ 1 ]-> width = 7 ; $array1 [ 1 ]-> height = 1 ;
$array1 [ 2 ]-> width = 2 ; $array1 [ 2 ]-> height = 9 ;
$array1 [ 3 ]-> width = 5 ; $array1 [ 3 ]-> height = 7 ;
$array2 [ 0 ]-> width = 7 ; $array2 [ 0 ]-> height = 5 ;
$array2 [ 1 ]-> width = 9 ; $array2 [ 1 ]-> height = 2 ;
function compare_by_area ( $a , $b ) $areaA = $a -> width * $a -> height ;
$areaB = $b -> width * $b -> height ;
if ( $areaA < $areaB ) return - 1 ;
> elseif ( $areaA > $areaB ) return 1 ;
> else return 0 ;
>
>
print_r ( array_udiff ( $array1 , $array2 , ‘compare_by_area’ ));
?>
The above example will output:
Array ( [0] => stdClass Object ( [width] => 11 [height] => 3 ) [1] => stdClass Object ( [width] => 7 [height] => 1 ) )
Example #2 array_udiff() example using DateTime Objects
class MyCalendar public $free = array();
public $booked = array();
?php
public function __construct ( $week = ‘now’ ) $start = new DateTime ( $week );
$start -> modify ( ‘Monday this week midnight’ );
$end = clone $start ;
$end -> modify ( ‘Friday this week midnight’ );
$interval = new DateInterval ( ‘P1D’ );
foreach (new DatePeriod ( $start , $interval , $end ) as $freeTime ) $this -> free [] = $freeTime ;
>
>
public function bookAppointment ( DateTime $date , $note ) $this -> booked [] = array( ‘date’ => $date -> modify ( ‘midnight’ ), ‘note’ => $note );
>
public function checkAvailability () return array_udiff ( $this -> free , $this -> booked , array( $this , ‘customCompare’ ));
>
public function customCompare ( $free , $booked ) if ( is_array ( $free )) $a = $free [ ‘date’ ];
else $a = $free ;
if ( is_array ( $booked )) $b = $booked [ ‘date’ ];
else $b = $booked ;
if ( $a == $b ) return 0 ;
> elseif ( $a > $b ) return 1 ;
> else return — 1 ;
>
>
>
// Create a calendar for weekly appointments
$myCalendar = new MyCalendar ;
// Book some appointments for this week
$myCalendar -> bookAppointment (new DateTime ( ‘Monday this week’ ), «Cleaning GoogleGuy’s apartment.» );
$myCalendar -> bookAppointment (new DateTime ( ‘Wednesday this week’ ), «Going on a snowboarding trip.» );
$myCalendar -> bookAppointment (new DateTime ( ‘Friday this week’ ), «Fixing buggy code.» );
// Check availability of days by comparing $booked dates against $free dates
echo «I’m available on the following days this week. \n\n» ;
foreach ( $myCalendar -> checkAvailability () as $free ) echo $free -> format ( ‘l’ ), «\n» ;
>
echo «\n\n» ;
echo «I’m busy on the following days this week. \n\n» ;
foreach ( $myCalendar -> booked as $booked ) echo $booked [ ‘date’ ]-> format ( ‘l’ ), «: » , $booked [ ‘note’ ], «\n» ;
>
?>
The above example will output:
I'm available on the following days this week. Tuesday Thursday I'm busy on the following days this week. Monday: Cleaning GoogleGuy's apartment. Wednesday: Going on a snowboarding trip. Friday: Fixing buggy code.
Notes
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], «data_compare_func»); .
See Also
- array_diff() — Computes the difference of arrays
- array_diff_assoc() — Computes the difference of arrays with additional index check
- array_diff_uassoc() — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
- array_udiff_assoc() — Computes the difference of arrays with additional index check, compares data by a callback function
- array_udiff_uassoc() — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
- array_intersect() — Computes the intersection of arrays
- array_intersect_assoc() — Computes the intersection of arrays with additional index check
- array_uintersect() — Computes the intersection of arrays, compares data by a callback function
- array_uintersect_assoc() — Computes the intersection of arrays with additional index check, compares data by a callback function
- array_uintersect_uassoc() — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
User Contributed Notes 9 notes
I think the example given here using classes is convoluting things too much to demonstrate what this function does.
array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.
To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function. If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff(). It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3]. Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].
For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0. Therefore, $a[1] is not returned from array_udiff() since it is present in $b.
function compare_ids($a, $b)
return ($a[‘id’] — $b[‘id’]);
>
function compare_names($a, $b)
return strcmp($a[‘name’], $b[‘name’]);
>
$ret = array_udiff($a, $b, ‘compare_ids’);
var_dump($ret);
$ret = array_udiff($b, $a, ‘compare_ids’);
var_dump($ret);
$ret = array_udiff($a, $b, ‘compare_names’);
var_dump($ret);
?>
Which returns the following.
In the first return we see that $b has no entry in it with an id of 10.
array(1) [0]=>
array(3) [«id»]=>
int(10)
[«name»]=>
string(4) «John»
[«color»]=>
string(3) «red»
>
>
?>
In the second return we see that $a has no entry in it with an id of 15 or 40.
array(2) [0]=>
array(3) [«id»]=>
int(15)
[«name»]=>
string(5) «Nancy»
[«color»]=>
string(5) «black»
>
[3]=>
array(3) [«id»]=>
int(40)
[«name»]=>
string(4) «John»
[«color»]=>
string(6) «orange»
>
>
?>
In third return we see that all names in $a are in $b (even though the entry in $b whose name is ‘John’ is different, the anonymous function is only comparing names).
array(0) >
?>
Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.
If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.
I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.
function compr_1 ( $a , $b ) $aVal = is_array ( $a ) ? $a [ ‘last_name’ ] : $a ;
$bVal = is_array ( $b ) ? $b [ ‘last_name’ ] : $b ;
return strcasecmp ( $aVal , $bVal );
>
$aEmployees = array(
array( ‘last_name’ => ‘Smith’ ,
‘first_name’ => ‘Joe’ ,
‘phone’ => ‘555-1000’ ),
array( ‘last_name’ => ‘Doe’ ,
‘first_name’ => ‘John’ ,
‘phone’ => ‘555-2000’ ),
array( ‘last_name’ => ‘Flagg’ ,
‘first_name’ => ‘Randall’ ,
‘phone’ => ‘666-1000’ )
);
$aNames = array( ‘Doe’ , ‘Smith’ , ‘Johnson’ );
$result = array_udiff ( $aEmployees , $aNames , «compr_1» );
print_r ( $result );
?>
Allowing me to get the «employee» that’s not in the name list:
Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )
Something interesting to note, is that the two arguments to the compare function don’t correspond to array1 and array2. That’s why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array. (Found this out the hard way.)
Quick example for using array_udiff to do a multi-dimensional diff
Returns values of $arr1 that are not in $arr2
$arr1 = array( array( ‘Bob’ , 42 ), array( ‘Phil’ , 37 ), array( ‘Frank’ , 39 ) );
$arr2 = array( array( ‘Phil’ , 37 ), array( ‘Mark’ , 45 ) );
$arr3 = array_udiff ( $arr1 , $arr2 , create_function (
‘$a,$b’ ,
‘return strcmp( implode(«», $a), implode(«», $b) ); ‘ )
);
PHP array_diff() function
In PHP, the array diff() method compares the contents of two or more arrays and produces an array containing the values from the first array that are not present in any of the other arrays. It can be used to quickly find the difference between two or more arrays.
What is the syntax of the array_diff() function in PHP?
array array_diff ( array $array1 , array $array2 [, array $. ] )
Parameters | Details |
---|---|
array1 | The first array to compare with other arrays – required |
array2 | Second array to make a comparison against- required |
array3, ... | Further arrays to compare against – optional |
It takes at least two arrays as arguments, and compares the values of all arrays passed as arguments, it returns an array containing the values from the first array ($array1) that are not present in any of the other arrays ($array2, …)
Examples
The following code will return an array containing the values from $array1 that are not present in $array2:
$array1 = array(1, 2, 3, 4); $array2 = array(3, 4, 5, 6); $diff = array_diff($array1, $array2); print_r($diff);
As you can see, the output is an array containing the values that were not included in $array2.
If you compare more than two arrays, it will return the values that are not present in all of them.
$array1 = array(1, 2, 3, 4); $array2 = array(3, 4, 5, 6); $array3 = array(5,6,7,8); $diff = array_diff($array1, $array2, $array3); print_r($diff);
As you can see, this method produces an array containing all of the values from the first array that aren’t in the other arrays.