Home > Software design >  php tow explode and compare
php tow explode and compare

Time:10-30

What I'm trying to do is pull repeats from two strings.

I show you the example.

$var_1 = blue, yellow, red, purple, black 
$var_2 = blue red, green, black

what I do initially is an explode

$var1 = explode(",", $var_1);
$var2 = explode(",", $var_2);

I count the elements to make a for

$nr1 = count($var2);
$nr2 = count($var2);
 
for($x = 0; $x < $nr1; $x  ){
  for($y = 0; $y < $nr2; $y  ){
    if (strcmp($var1[$x], $var2[$y]) !== 0) {
      echo ($var1[$x] == $var2[$y]) ? 'true<br>' : $var1[$x].'<br>';
    }
  }
}

and I'm getting repeated results and I'm missing in var2

blue blue blue yellow yellow yellow red red red purple purple purple
black black

when the result I expect is

blue, yellow, red, purple, red, green, black

Can somebody help me?

CodePudding user response:

You can array_merge() the 2 arrays and then run array_unique() to remove duplicates like this

$var_1 = 'blue, yellow, red, purple, black';
$var_2 = 'blue, red, green, black';

$No_Dups = array_unique( array_merge( explode(",", $var_1), explode(",", $var_2)));
print_r($merged);

RESULT

Array
(
    [0] => blue
    [1] =>  yellow
    [2] =>  red
    [3] =>  purple
    [4] =>  black
    [7] =>  green
)
  • Related