Php 使用数组_diff和数组_diff_assoc时都返回0

Php 使用数组_diff和数组_diff_assoc时都返回0,php,arrays,array-difference,Php,Arrays,Array Difference,你好,由于某种原因,我遇到了一个奇怪的问题array_diff为我返回了一个0,我不明白为什么我有下面的数组 $a = [0 => 'blue'] $b = [0 => 'blue', 0 => 'red', 0 => 'brown', 0 => 'yellow'] 当我尝试的时候 $C = array_diff($a, $b) 我得到0返回 与相同的结果 array_diff_assoc 有什么想法吗 谢谢。请参阅此演示,并在评论中逐步解释。您可能希望删除

你好,由于某种原因,我遇到了一个奇怪的问题array_diff为我返回了一个0,我不明白为什么我有下面的数组

$a = [0 => 'blue']

$b = [0 => 'blue', 0 => 'red', 0 => 'brown', 0 => 'yellow']
当我尝试的时候

$C = array_diff($a, $b)
我得到
0
返回

与相同的结果

array_diff_assoc
有什么想法吗


谢谢。

请参阅此演示,并在评论中逐步解释。您可能希望删除手动索引(
0=>
),并反转参数

<?php

// Your uncorrected input.
$a = [0 => 'blue'];
$b = [0 => 'blue', 0 => 'red', 0 => 'brown', 0 => 'yellow'];

var_dump($a);
/*
array(1) {
  [0]=>
  string(4) "blue"
}
*/

var_dump($b);
/*
One element, because you've OVERWRITTEN 'red' and 'brown' by 'yellow',
because you've assigned them all to the same key.
array(1) {
  [0]=>
  string(6) "yellow"
}
*/

var_dump(array_diff($a, $b));
/*
'blue' is not present in $b.
array(1) {
  [0]=>
  string(4) "blue"
}
*/

// Your input.
$a = ['blue'];
$b = ['blue', 'red', 'brown', 'yellow'];

var_dump($a);
/*
array(1) {
  [0]=>
  string(4) "blue"
}
*/

var_dump($b);
/*
Four elements, because the array is automatically numerically indexed with an 'auto increment' key.
array(4) {
  [0]=>
  string(4) "blue"
  [1]=>
  string(3) "red"
  [2]=>
  string(5) "brown"
  [3]=>
  string(6) "yellow"
}
*/


/*
Loosely translated from the docs:
array_diff() compares first argument against one or more other arrays and returns the values
in first array that are not present in any of the other arrays.
*/

var_dump(array_diff($a, $b));
/*
Nothing from $a is not present in $b.
array(0) {
}
*/

var_dump(array_diff($b, $a));
/*
Red, brown and yellow are not present in $a.
array(3) {
  [1]=>
  string(3) "red"
  [2]=>
  string(5) "brown"
  [3]=>
  string(6) "yellow"
}
*/
还值得一读,以了解
array\u diff
的确切比较。