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

StackOverflow https://stackoverflow.com/questions/16483421

  •  21-04-2022
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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

<?php

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

 var_dump($diff)

?>

add in $a2=array() one element

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top