Jump to content

printing a message in a for loop


hamburgerlove413
Go to solution Solved by kicken,

Recommended Posts

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 by hamburgerlove413
Link to comment
Share on other sites

  • Solution

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
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.