This works
$arr = array_merge(array_diff($words, array("the","an"));
Why doesn’t this work?
$common consists of 40 words in an array.
$arr = array_merge(array_diff($words, $common));
Is there another solution for this?
For Reference:
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words(&$string) {
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
$words = explode(" ",$string);
$arr = array_merge(array_diff($words, array("the","an")));
print_r($arr);
}
?>
White-spaces are evil, sometimes..
fgetswith only one parameter will return one line of data from the filehandle provided.Though, it will not strip off the trailing new-line (
"\n"or whatever EOL character(s) is used) in the line returned.Since
common.txtseems to have one word per line, this is the reason why php won’t find any matching elements when you usearray_diff.Rephrase:
$commonwill have a trailing line-break the way you are doing it now.Alternative solutions 1
If you are not going to process the entries in
common.txtI’d recommend you to take a look at php’s functionfile, and use that in conjunction witharray_maptortrimthe lines for you.Alternative solutions 2
After @MarkBaker saw the solution above he made a comment saying that you might as well pass a flag to
fileto make it work in the same manner, there is no need to call array_map to "fix" the entries returned.