h_h
h_h

Reputation: 1231

PHP array values and strpos function

I have been using this piece of code to compare two values, I am getting the matched items exactly, The only problem is with non matched items.

$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(strpos($parts1[$i],$parts2[$j]) !== false)
    {
      $match[] = $parts1[$i];
    }
    else
    {
      $nomatch[] = $parts2[$j];
    }
  }
}

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

And what i am getting as result is

Array ( [0] => red [1] => green [2] => blue ) 
Array ( [0] => green [1] => blue [2] => red [3] => blue [4] => red [5] => green [6] =>     
red [7] => green [8] => blue )

Array 1 is giving the exact matched values but array 2 is giving absurd results instead of yellow.

Upvotes: 1

Views: 274

Answers (2)

PiTheNumber
PiTheNumber

Reputation: 23542

Here you go:

for($i=0; $i< count($parts1); $i++)
{
  $matched = false;
  for($j=0; $j< count($parts2); $j++)
  {
    if(strpos($parts1[$i],$parts2[$j]) !== false)
    {
      $match[] = $parts1[$i];
      $matched = true;
      break;
    }
  }
  if (!$matched)
  {
    $nomatch[] = $parts1[$i];
  }
}

Demo: http://codepad.org/J6lmOUVO

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270637

Because you are nesting loops, for each iteration of the outer loop you must iterate over every element of the inner loop. The non-matching extraneous values you see are all those extra inner iterations.

If you must allow partial matches with strpos(), use the following:

foreach ($parts1 as $p) {
  // Flag that the current value has been matched
  $matched = FALSE;
  foreach ($parts2 as $p2) {
    if (strpos($p, $p2) !== FALSE) {
      $matches[] = $p;
      $matched = TRUE;
    }
  }
  // If the loop was proceed with no match, add to non-matches
  if (!$matched) {
    $nomatch[] = $p;
  }
}

var_dump($matches);
array(3) {
  [0] =>
  string(3) "red"
  [1] =>
  string(5) "green"
  [2] =>
  string(4) "blue"
}
var_dump($nomatch);
array(1) {
  [0] =>
  string(6) "yellow"
}

Upvotes: 1

Related Questions