为什么array_diff()比较两个不同的数组相同并返回空结果? [英] Why array_diff() compares two different arrays as same and returns empty result?

查看:98
本文介绍了为什么array_diff()比较两个不同的数组相同并返回空结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

$a1 = array(31001);
$a2 = array(31001, 31002);
$diff = array_diff($a1, $a2);
var_dump($diff);

根据PHP文档,我期望array_diff将返回 array(0 => 31002):

I was expecting that array_diff will return array(0 => 31002) according to PHP documentation:

返回一个数组,其中包含array1中所有不包含的条目存在于其他任何数组中.

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 ?

这是 PHPfiddle示例.

感谢您的帮助或有用提示.

Thanks for any help or helpful hints.

推荐答案

准确阅读文档.在 $ a1 中存在但在 $ a2 中不存在的一组值是空的: $ a1 仅包含一个元素(31001 ),也出现在 $ a2 中.

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.

您要获取 $ a2 中存在的所有值,而不是 $ a1 中存在的所有值,因此必须切换数组的顺序,然后传递给 array_diff():

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);

这篇关于为什么array_diff()比较两个不同的数组相同并返回空结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆