Building a Number Guessing Game in PHP

Believe it or not, but the last 13 or so posts have all been leading up to this one. Generating random numbers, capturing user input, using colors on the command-line, pluralizing words, and then some are all being utilized in this simple number guessing game.

The script itself generates a random number between 1 and 100, asks the user to guess, advises them if they are too high or too low then tells them how many guesses it took them to guess the number:


$number  = rand(1, 100
$guesses = 0
$won	 = false
$handle  = fopen('php://stdin', 'r'

echo "nI'm thinking of a number between 1 and 100...nCan you guess the number?nn"

while (!$won)
	echo 'What is your guess? '

	$guess = trim(fgets($handle

	if (preg_match('/d/', $guess))
		if ($guess > $number)
			echo "3333[0mn"
		elseif ($guess < $number)
			echo "3333[0mn"
		elseif ($guess == $number)
			echo "33nYou guessed it!33[0mn"
			printf('It took you %d ' . ngettext('guess', 'guesses', $guesses) . "!n",  $guesses


To run the script, just execute it from the command-line:

php -f number-guess.php

Substitute number-guess.php for whatever you named the script and guess away!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.