People,
Have a look at this foreach code:
<?php
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//script 4: https://stackoverflow.com/questions/13795789/check-if-string-contains-word-in-array
$content = "There are ***** all over the place!";
$banned_words = array('evil', 'devil', 'cruelty');
foreach($banned_words as $band) {
$place = strpos($content, $band);
if (!empty($place)) {
echo "Script 4 - Found Banned Word: $band";
exit;
} else {
echo "No banned words found!";
}
}
?>
As you can see the number of loops that the foreach would make is dependant on the number of items in the array. Since the array has 3 items then from my test the foreach is getting looped 3 times.
Now, how do I know it is getting looped 3 times ? i know because of what is being echoed:
No banned words found!No banned words found!No banned words found!
You can see the phrase in the echo has been echoed 3 times. That means, the ELSE got triggered 3 times. Which also means the foreach got triggered 3 times. Right ?
Now, let’s change the code a little so that the IF->THEN gets triggered instead:
<?php
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//script 4: https://stackoverflow.com/questions/13795789/check-if-string-contains-word-in-array
$content = "There are devils all over the place!";
$banned_words = array('evil', 'devil', 'cruelty');
foreach($banned_words as $band) {
$place = strpos($content, $band);
if (!empty($place)) {
echo "Script 4 - Found Banned Word: $band";
exit;
} else {
echo "No banned words found!";
}
}
?>
The echo is now:
Script 4 - Found Banned Word: evil
The script should have found devil too but it did not. And that is due to the loop getting halted after the 1st loop.
And so, my question is, why does the foreach only loop until the 1st match has been met ? Why doesn’t it check for the other matches too ? Why does it not for the words in the other array(s) ?
I mean, I did not create any condition for it to stop as soon as one match has been found. Now did I ? I did not use the DoWhile.
(When I used to build bots, I used to use the loop like this: Loop(total number), LoopWhile, LoopWhile Not. And, I know the DoWhile is the same as the LoopWhile we have).
Now, how to change the code so the script checks for matches for all the words present in the array ? In our case, the script should loop thrice checking for all 3 different words. And the result should show TRUE echoes like this:
Script 4 - Found Banned Word: evil
Script 4 - Found Banned Word: devil
Or, show like this:
Script 4 - Found Banned Word: evil
Script 4 - Found Banned Word: evil
No banned words found! (when checking for “cruelty” in our example).