Reputation: 1707
I didn't find much resource online about this. I have 2 array. I want to remove all the items that doesn't exists on the other array.
Array 1
array(3) {
[0]=>
string(8) "download"
[1]=>
string(4) "test"
[2]=>
string(4) "edit"
}
Array 2
array(3) {
[0]=>
string(8) "download"
[1]=>
string(10) "{category}"
[2]=>
string(4) "edit"
}
So the final array I should be getting is something like
array(3) {
[0]=>
string(8) "download"
[2]=>
string(4) "edit"
}
Upvotes: 0
Views: 778
Reputation: 5071
array_intersect()
is what you need:
<?php
$array1 = array("download", "test", "edit");
$array2 = array("download", "category", "edit");
$array3 = array_intersect($array1, $array2);
var_dump($array3);
?>
More here: http://php.net/manual/en/function.array-intersect.php
Upvotes: 4
Reputation: 121
you can do it with 2 foreach :
<?php
$array1 = array("download", "test", "edit");
$array2 = array("download", "category", "edit");
$array3 = array();
foreach($array1 as $value){
foreach($array2 as $value2){
if($value === $value2){
$array3[] = $value;
break;
}
}
}
print_r($array3);
Upvotes: 0
Reputation: 23
you can use the array_diff function described here
$array3 = array_diff($array1, $array2)
would be all the elements that occur in array1 that do not also occur in array2
For finding overlaps, you can use the similar array_intersect function
Upvotes: 2