开发者

array_diff not working as expected ? What could be the reason?

开发者 https://www.devze.com 2023-04-03 07:29 出处:网络
I have two开发者_运维技巧 arrays . Check the code $array1 = array(0=>\'215\',1=> \'225\');

I have two开发者_运维技巧 arrays .

Check the 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 am getting answers as

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

But according to array_diff manual it should be

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

What could be the problem


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 running,


It was not working for me (dont know why) so I changed the code to calculate difference in two array

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

0

精彩评论

暂无评论...
验证码 换一张
取 消