Search code examples
phparraysforeachstrpos

Compare elements of two arrays php


So I have two arrays:

$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');

$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');

I need to compare elements of input phrases array with bad words array and output new array with phrases WITHOUT bad words like this:

$outputarray = array('nothing-bad-here', 'more-clean-stuff','one-more-clean', 'clean-clean');

I tried doing this with two foreach loops but it gives me opposite result, aka it outputs phrases WITH bad words. Here is code I tried that outputs opposite result:

function letsCompare($inputphrases, $badwords)
{
    foreach ($inputphrases as $inputphrase) {

        foreach ($badwords as $badword) {

            if (strpos(strtolower(str_replace('-', '', $inputphrase)), strtolower(str_replace('-', '', $badword))) !== false) {
                $result[] = ($inputphrase);

            }
        }
    }
return $result;
}

$result = letsCompare($inputphrases, $badwords);
print_r($result);

Solution

  • this is not a clean solution, but hope, you'll got what is going on. do not hesitate to ask for clearence. repl.it link

    $inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
    
    
    $new_arr = array_filter($inputphrases, function($phrase) {
      $badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
      $c = count($badwords);
      for($i=0; $i<$c; $i++) {
        if(strpos($phrase, $badwords[$i]) !== false){
          return false;
        }
      }
      return true;
    });
    
    print_r($new_arr);