hamburgerlove413 Posted October 11, 2013 Share Posted October 11, 2013 (edited) 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. Edited October 11, 2013 by hamburgerlove413 Quote Link to comment Share on other sites More sharing options...
Solution kicken Posted October 11, 2013 Solution 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'; } Quote Link to comment Share on other sites More sharing options...
hamburgerlove413 Posted October 11, 2013 Author Share Posted October 11, 2013 Thank You! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.