Jump to content

foreach dosent work why.


redarrow

Recommended Posts

foreach wont work why please cheers.

[code]
<?php

$sentence="hi there i think your a word1";

$words=array("word1","word2","word3","word4");

foreach($words AS $bad){

if(eregi($bad,$sentence)){

echo " sorry but your useing bad words please try agin but be nice!";
exit;

}else{

echo" your words are lovly";
exit;
}
}

?>
[/code]

[b]edit(shoz): edited for language[/b]
Link to comment
Share on other sites

[code]
<?php

$sentence="hi there i think your a word1";

$words=array("word1","word2","word3","word4");

foreach($words AS $bad){
if(strpos($sentence,$bad)){
$badword = 'yes';
}
}
if($badword =='yes'){
echo " sorry but your useing bad words please try agin but be nice!";
exit;
}else{

echo" your words are lovly";
exit;
}


?>
[/code]
Using strpos because it is the fastest way according to the manual.
Link to comment
Share on other sites

The problem with your way is that it would always exit the loop on the first iteration.

If the first word in your array was in the sentence, it would have shown up as being a bad string, but because the first word in the array wasn't in the sentence, it was saying that the sentence was ok and then exiting.

The way i did it, it loops through all of the words and if any of them are in the sentence it simply makes the variable $badwords equal yes.

Then after the loop has finished it checks to see if the $badwords does equal yes, and if so it must mean that one of the bad words was found.
Link to comment
Share on other sites

Ah yes shoz, i fogot to change them on my post too.

Also, it would make the script run quicker to add a break; in if a bad word is found because it only needs to know if one of the words is found:
[code]
<?php

$sentence="hi there i think your a word1";

$words=array("word1","word2","word3","word4");

foreach($words AS $bad){
if(strpos($sentence,$bad)){
$badword = 'yes';
break;//break out of the loop if a bad word is found...continuing is unnecessary
}
}
if($badword =='yes'){
echo " sorry but your useing bad words please try agin but be nice!";
exit;
}else{

echo" your words are lovly";
exit;
}


?>
[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.