Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array comparison and finding matched and non matched items

Tags:

php

I have been using this script for finding matched and nonmatched array items.

My code is.

$filter1 = "red,green,blue,yellow";         
$parts1 = explode(',', $filter1);

$filter2 = "red,green,blue";        
$parts2 = explode(',', $filter2);

for($i=0; $i< count($parts1); $i++)
{

    for($j=0; $j< count($parts2); $j++)
    {

        if($parts1[$i] == $parts2[$j])
        {
            $match[] = $parts1[$i];
        } else {
            $nomatch[] = $parts1[$i];
        }
    }
}

print_r($match);
echo "<br>";
print_r($nomatch);

By using this code i am only getting the matched items and not nonmatched. Can anybody help. Thanks in advance.

like image 295
h_h Avatar asked Mar 27 '26 14:03

h_h


1 Answers

You can try using array_intersect and array_diff

$filter1 = "red,green,blue,yellow";         
$parts1 = explode(',', $filter1);

$filter2 = "red,green,blue";        
$parts2 = explode(',', $filter2);

$match = array_intersect($parts1, $parts2);
$nomatch = array_diff($parts1, $parts2);

var_dump($match,$nomatch);

Output

array
  0 => string 'red' (length=3)
  1 => string 'green' (length=5)
  2 => string 'blue' (length=4)
array
  3 => string 'yellow' (length=6)
like image 152
Baba Avatar answered Mar 29 '26 02:03

Baba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!