$array1 = array("a","b");
$array2 = array("b","c");
I want the following array from above arrays containing items which are not common in both arrays.
$output = array("a","c");
I have tried folloing
$output = array_diff($array1,$array2);
How can do it. Thanks.
Use:
$array1 = array("a","b");
$array2 = array("b","c");
$output = array("a","c");
$output = array_merge(array_diff($array1,$array2),array_diff($array2,$array1));
print_r($output);
Just make subtraction of union and intersection:
$array1 = array("a","b");
$array2 = array("b","c");
$output = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
So I read earlier today about how array_merge was considered slow. I also read the same about array_diff, specifically here. This got me to thinking that using both at once could be particularly expensive, so I put the following experiment together:
I expanded upon merlyn's function to come up with this:
function multiArrayUnique($array1, $array2)
{
//leaves array1 intact
$arrayFrom1=$array1;
$arrayAgainst = array_flip($array2);
foreach ($arrayFrom1 as $key => $value) {
if(isset($arrayAgainst[$value])) {
unset($arrayFrom1[$key]);
}
}
//arrayFrom1=array("a");
$arrayFrom2=$array2;//b,c
$arrayAgainst = array_flip($array1);//a,b
foreach ($arrayFrom2 as $key => $value) {
if(isset($arrayAgainst[$value])) {
unset($arrayFrom2[$key]);
}
}
//arrayFrom2=array("c");
foreach ($arrayFrom2 as $item) {
array_push($arrayFrom1, $item);
}
return $arrayFrom1;
}
Using the OP's example, this function also returns array("a","c")
.
Now, that is a monstrous amount of code, and it it difficult to read... but, here is the efficiency it buys on a large data set:
$a1 = range(0,25000);
$a2 = range(15000,50000);
$start=microtime(true);
$output = array_diff(array_merge($a1, $a2), array_intersect($a1, $a2));
$end=microtime(true);
echo $end-$start."<hr>";
7.5844340324402
$start=microtime(true);
$output = array_merge(array_diff($a1,$a2),array_diff($a2,$a1));
$end=microtime(true);
echo $end-$start."<hr>";
6.551374912262
$start=microtime(true);
$result=multiArrayUnique($a1,$a2);
$end=microtime(true);
echo $end-$start."<hr>";
0.21001195907593
So while the function's code is considerably more complex, and may have other limitations, it's implementation is still a one-liner, and the processing time is 14x faster.