Question

I have two arrays in my script.

$array1 = array("a" =>'1','2','3','4','5','6','7','8','9','10');
$array2 = array("b" => '1','3','4','6','7','8','10');

I want to compare those array and find items which is exist in $array1 but not in $array2.
For this I use array_diff($array1, $array2) which gives o/p like this Array ( [0] => 2 [3] => 5 [7] => 9 ).
But I want o/p like this Array ( [0] => 2 [1] => 5 [2] => 9 )

Was it helpful?

Solution 2

You could sort the array after the difference using sort().

$array1 = array("a" =>'1','2','3','4','5','6','7','8','9','10');
$array2 = array("b" => '1','3','4','6','7','8','10');
$diff = array_diff($array1, $array2);
sort($diff);

http://codepad.viper-7.com/yREvAg

Or like others are writing, you could use the array_values()

OTHER TIPS

Try with array_values:

$output = array_values(array_diff($array1, $array2));

Output:

array (size=3)
  0 => string '2' (length=1)
  1 => string '5' (length=1)
  2 => string '9' (length=1)

use array_diff

$array1 = array("a" =>'1','2','3','4','5','6','7','8','9','10');
$array2 = array("b" => '1','3','4','6','7','8','10');

$diff = array_diff($array1, $array2);

For reset keys, use array_values

$reset = array_values($diff);
$temp = array_diff($array1, $array2)
$result = array();
foreach($temp as $key => $value){
     $result[] = $value;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top