Why array_diff() compares two different arrays as same and returns empty result? [closed]

廉价感情. 提交于 2021-02-10 23:16:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!