37

I'm trying to compare two arrays and get only the values that exist on both arrays but, unfortunately, I can't find the right array function to use...

I found the array_diff() function: http://php.net/manual/en/function.array-diff.php

But it's for the difference of the both arrays.

Example:

$array1 = array("**alpha**","omega","**bravo**","**charlie**","**delta**","**foxfrot**");
$array2 = array("**alpha**","gamma","**bravo**","x-ray","**charlie**","**delta**","halo","eagle","**foxfrot**");

Expected Output:

$result = array("**alpha**","**bravo**","**charlie**","**delta**","**foxfrot**");
Julian Paolo Dayag
  • 3,562
  • 3
  • 20
  • 32

3 Answers3

103

Simple, use array_intersect() instead:

$result = array_intersect($array1, $array2);
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
2

OK.. We needed to compare a dynamic number of product names...

There's probably a better way... but this works for me...

... because....Strings are just Arrays of characters.... :>}

//  Compare Strings ...  Return Matching Text and Differences with Product IDs...

//  From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";   

$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";   

$ProductNames = array(
    $productID1 => $productName1,
    $productID2 => $productName2
);


function compareNames($ProductNames){   

    //  Convert NameStrings to Arrays...    
    foreach($ProductNames as $id => $product_name){
        $Package1[$id] = explode(" ",$product_name);    
    }

    // Get Matching Text...
    $Matching = call_user_func_array('array_intersect', $Package1 );
    $MatchingText = implode(" ",$Matching);

    //  Get Different Text...
    foreach($Package1 as $id => $product_name_chunks){
        $Package2 = array($product_name_chunks,$Matching);
        $diff = call_user_func_array('array_diff', $Package2 );
        $DifferentText[$id] = trim(implode(" ", $diff));
    }

    $results[$MatchingText]  = $DifferentText;              
    return $results;    
}

$Results =  compareNames($ProductNames);

print_r($Results);

// Gives us this...
[EcoPlus Premio Jet] 
        [abc123] => 600
        [xyz789] => 800
Bill Warren
  • 392
  • 8
  • 11
0

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

Lonare
  • 3,581
  • 1
  • 41
  • 45
  • The "note" for `array_intersect` is significant. The keys are preserved...and I think, being added if they don't exist. I am comparing `$a = array(1113,1135,1152);` and `$b=(1113,1135);` as `$res = array_intersect($a,$b);` and the result being sent back to Javascript is an object: `{"1":"1113","2":"1135"}` – rolinger Jan 28 '23 at 02:49