Reputation: 133
Here is two numeric array:
$a = array(0 => '1,3');
$b = array(
0 => '1,2,4',
1 => '1,2',
2 => '4,3',
3 => '2,4',
4 => '1,3'
);
I want to compare these two arrays and find their same values. For example, in this case [0] => 1,3
in the first array is matching with [4] => 1,3
in the second one.
I tried to achieve this by using array_diff
but with no success. Can any one help this out?
Upvotes: 0
Views: 75
Reputation: 99484
Use array_search()
to search within array a given value:
$a = array(0 => '1,3');
$b = array(
0 => '1,2,4',
1 => '1,2',
2 => '4,3',
3 => '2,4',
4 => '1,3'
);
foreach ($a as $val) {
if ($key = array_search($val, $b)) {
echo "'$val' is matched in '$key' index";
break;
}
}
Output:
'1,3' is matched in '4' index
You can also do the following:
$match = array();
foreach ($a as $val) {
if (array_search($val, $b)) {
$match[] = $val;
}
}
print_r($match);
Output:
Array
(
[0] => 1,3
)
Update:
As the OP mentioned, for this purpose we use array_intersect()
function as well:
$a = array(0 => '1,3');
$b = array(
0 => '1,2,4',
1 => '1,2',
2 => '4,3',
3 => '2,4',
4 => '1,3'
);
print_r(array_intersect($a, $b));
Output:
Array
(
[0] => 1,3
)
Upvotes: 1