简体   繁体   中英

Filter an array with array_filter

I have an array of words and an array of stopwords. I want to remove those words from the array of words that are in the stopwords array, but the code returns all words:

function stopwords($x){
      return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
    };

$filteredArray = array_filter($wordArray, "stopwords");

Why?

$wordArray = ["hello","red","world","is"];

function stopwords($x){
      return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
    };

$filteredArray = array_filter($wordArray, "stopwords");
var_dump($filteredArray);

# results out:
array(2) {
   [0] =>   string(5) "hello"   
   [2] =>   string(5) "world"
}

What do you think it was going to return?

Is your input '$wordArray' a string, or an array?

// Should be an Array
$wordArray = array('he', 'is', 'going', 'to', 'bed' );

// Should return boolean
function stopwords ($x)
{
return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
}

//filter array
$filter = array_filter($wordArray, "stopwords");

// Output
echo "< pre>";
print_r($filter);

// Result
Array
(
[0] => he
[2] => going
[4] => bed
)

Try this..

    $words = array('apple','boll','cat','dog','elephant','got');
        $stopwords = array('cat','apple');

       foreach($words as $k=>$v)
        {
        if(in_array($v,$stopwords)){
            unset($words[$k]);  
        }

      }
print_r($words);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM