问题
I have this code:
$a1 = array(31001);
$a2 = array(31001, 31002);
$diff = array_diff($a1, $a2);
var_dump($diff);
I was expecting that array_diff will return array(0 => 31002)
according to PHP documentation:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
However posted code returns empty array. Anyone can explain me why is this happening and how to get correct result ?
Here is PHPfiddle example.
Thanks for any help or helpful hints.
回答1:
Read the documentation exactly. The set of values that are present in $a1
and not present in $a2
is empty: $a1
just contains one element (31001
), which is also present in $a2
.
You want to get all values that are present in $a2
, but not in $a1
, so you have to switch the order of the arrays, you pass to array_diff()
:
$diff = array_diff($a2, $a1);
回答2:
try this, it will work
$diff = array_diff($a2, $a1);
it will give
Array
(
[1] => 31002
)
but when you try
$a1 = array(31001);
$a2 = array(31002, 31001);
$diff = array_diff($a2, $a1);
it will give
Array
(
[0] => 31002
)
array_diff will return array(0 => 31002), in this condition only, it is due to index location of elements
回答3:
<?php
$a1 = array(31001);
$a2 = array(31002);
$diff = array_diff($a1, $a2);
var_dump($diff)
?>
add in $a2=array() one element
来源:https://stackoverflow.com/questions/16483421/why-array-diff-compares-two-different-arrays-as-same-and-returns-empty-result