Search code examples
phpstr-replacestrsplit

hangman "word" in php


I am trying to do something similar to hangman where when you guess a letter, it replaces an underscore with what the letter is. I have come up with a way, but it seems very inefficient and I am wondering if there is a better way. Here is what I have -

<?
$word = 'ball';
$lettersGuessed = array('b','a');

echo str_replace( $lettersGuessed , '_' , $word ); // __ll

echo '<br>';

$wordArray = str_split ( $word );

foreach ( $wordArray as $letterCheck )
{

    if ( in_array( $letterCheck, $lettersGuessed ) )
    {
        $finalWord .= $letterCheck;
    } else {
        $finalWord .= '_';
    }

}

echo $finalWord; // ba__
?>

str_replace does the opposite of what I want. I want what the value of $finalWord is without having to go through a loop to get the result I desire.


Solution

  • If I am following you right you want to do the opposite of the first line:

    echo str_replace( $lettersGuessed , '_' , $word ); // __ll
    

    Why not create an array of $opposite = range('a', 'z'); and then use array_diff () against $lettersGuessed, which will give you an array of unguessed letters. It would certainly save a few lines of code. Such as:

    $all_letters = range('a', 'z');
    $unguessed = array_diff ($all_letters, $lettersGuessed);
    echo str_replace( $unguessed , '_' , $word ); // ba__