hamburgerlove413 Posted October 11, 2013 Share Posted October 11, 2013 Hello, I have a phrase guessing game I'm working on, and I'm currently trying to add some validation to it, and have a problem. I have a for loop with an if statement inside: if (preg_match("/^[a-zA-Z]$/", $guess)) { if (in_array($guess, $wordArray)) { for ($i=0; $i < $letterCount; $i++) { if ($guess == $wordArray[$i] && $visibleArray[$i] == 0) { $visibleArray[$i] = 1; print "<span class='success'>" .$guess . " is correct! </span>"; } else if ($guess == $wordArray[$i] && $visibleArray[$i] == 1) { print "<span class='error'>You already guessed that letter!</span>"; } } my problem is, if more than one of the same letter,say, three a's, is in the phrase to be guessed, it prints out the error or success message three times. What would be the best way to approach this to have it only print it once? I was thinking I could assign the messages to a variable, and then use a conditional and strlen, substr to trim them down? I'm hoping there's something easier though. Link to comment https://forums.phpfreaks.com/topic/282899-printing-a-message-in-a-for-loop/ Share on other sites More sharing options...
kicken Posted October 11, 2013 Share Posted October 11, 2013 Don't print the message from within the loop. Just set a variable (ie, $found) to true if the letter is found within the word. After the loop, check if $found is true or false and print the appropriate message. $found=false; //Assuming not found for ($i=0; $i<$letterCount; $i++){ if (...){ $found=true; } } if ($found) { print 'Correct'; } else { print 'Oops'; } Link to comment https://forums.phpfreaks.com/topic/282899-printing-a-message-in-a-for-loop/#findComment-1453606 Share on other sites More sharing options...
hamburgerlove413 Posted October 11, 2013 Author Share Posted October 11, 2013 Thank You! Link to comment https://forums.phpfreaks.com/topic/282899-printing-a-message-in-a-for-loop/#findComment-1453609 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.