Does Array_diff not work as expected? What could be the reason?

I have two arrays .
Check code

$array1 = array(0=>'215',1=> '225'); $array2 = array(0=>'225'); $diff_result = array_diff($array1, $array2); $diff = array_values($diff_result); print_r($array1);echo "<br>"; print_r($array2);echo "<br>"; print_r($diff_result);echo "<br>"; print_r($diff); 

Now I get answers like

 Array ( [0] => 215 [1] => 225 ) Array ( [0] => 225 ) Array ( [0] => 215 [1] => 225 ) Array ( [0] => 215 [1] => 225 ) 

But according to array_diff, the manual should be

 Array ( [0] => 215 [1] => 225 ) Array ( [0] => 225 ) Array ( [0] => 215 ) Array ( [0] => 215 ) 

What could be the problem

+4
source share
2 answers

This did not work for me (I donโ€™t know why) , so I changed the code to calculate the difference in the two arrays

 for ($i = 0; $i < count($array2); $i++) { for ($j = 0; $j < count($array1); $j++) { if(!in_array($array1[$j],$array2)){ $resArr[] = $array1[$j]; } } } print_r($array1);echo "<br>"; print_r($array2);echo "<br>"; print_r($resArr);echo "<br>"; 

Thanks for the time

+1
source

I ran your code as is and I got the correct results.

 $array1 = array(0=>'215',1=> '225'); $array2 = array(0=>'225'); $result = array_diff($array1, $array2); $diff_result = array_diff($array1, $array2); $diff = array_values($diff_result); print_r($array1);echo "<br>"; print_r($array2);echo "<br>"; print_r($diff_result);echo "<br>"; print_r($diff); 

Output:

 Array ( [0] => 215 [1] => 225 ) Array ( [0] => 225 ) Array ( [0] => 215 ) Array ( [0] => 215 ) 

my php -v

 PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch (cli) (built: May 2 2011 23:18:30) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies 

what version of php are you using

+1
source

All Articles