0

I'm making a little hangman game, and I want to sort the guesses the person makes in order of the actual word; Here is my code:

$word = "peach";
$_SESSION['letters'] = str_split($word);

ˆThat is where I make the word into an array, and I want when correct letters are added to an array, that they be sorted in order of the word. Is there any way I could do this, or another way I could write it? Thank you for your help.

3
  • 1
    I have no idea what you are trying to say. Can you give an example of what you would like? Commented Jan 10, 2014 at 2:16
  • @Mike So if I had the guesses a, c, and h, then I would want it to echo out as blank, blank, a, c, h (without commas) if the word was peach. Commented Jan 10, 2014 at 2:21
  • I meant to put the first 3 letters in a separate order, sorry Commented Jan 10, 2014 at 2:32

2 Answers 2

1

I misunderstood. Try this:

<?php
$guess = 'reach';
$guess_array = str_split($guess);
$word = 'peach';
$word_array = str_split($word);

$result = '';
foreach($word_array as $letter)
{
    if(in_array($letter, $guess_array))
    {
        $result .= $letter;
    }
    else
    {
        $result .= '_';
    }
}
echo($result);
// outputs: "_each"
?>
Sign up to request clarification or add additional context in comments.

1 Comment

I don't want it sorted alphabetically, I'd like to have it sorted in the order of the word
1

I think you're probably going about it wrong. You don't need to sort the array. Just set an array with the letters in the word and another array with the guesses. Then loop over the array with the word and see if the respective value is found in the guesses array. Something like this:

$word = "rumplestiltskin";    
$letters = str_split($word);

// Assume the user gets at least 6 guesses:
$guesses = array('r', 's', 't', 'l', 'n', 'e');

// Display the letters guessed correctly
foreach ($letters as $letter) {
    // Set both to lower case just in case
    if (in_array(strtolower($letter), array_map('strtolower', $guesses)) === true) {
        echo " $letter ";
    }
    else {
        echo " _ ";
    }
}

// Produces: r _ _ _ l e s t _ l t s _ _ n

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.