Skip to content
Advertisement

Merge 2 arrays and keep ONLY duplicates [closed]

So, i have 2 arrays which look like this:

$a = array(1,3,5);
$b = array(2,3,4,5);

The expected result should look like this:

array(3,5);

Is there a quick and easy way to achieve my expected result? 🙂

Advertisement

Answer

Option One:

$a = array(1,3,5);
$b = array(2,3,4,5);
$result = array_intersect($a, $b);
print_r($result);

Option 1 output:

Array
(
    [1] => 3
    [2] => 5
)

Option 2:

$a = array(1,3,5);
$b = array(2,3,4,5);
$resultTwo = [];
foreach($a as $val){
    if(in_array($val, $b)){
        $resultTwo[] = $val;
    }
}
print_r($resultTwo);

Option 2 Output (unlike option 1, the array index starts from 0):

Array
(
    [0] => 3
    [1] => 5
)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement