Reputation: 655
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.
Upvotes: 0
Views: 92
Reputation: 81
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"
?>
Upvotes: 1
Reputation: 24383
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
Upvotes: 1