Siva Shanker
Siva Shanker

Reputation: 133

Compare two arrays to find their same values

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

Answers (1)

Hashem Qolami
Hashem Qolami

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

Related Questions