Building a Number Guessing Game in PHP

Josh Sherman
1 min read
Software Development 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?\n\n";

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

	$guess = trim(fgets($handle));

	if (preg_match('/\d/', $guess))
		if ($guess > $number)
			echo "\033[0;31mToo high...\033[0m\n";
		elseif ($guess < $number)
			echo "\033[0;31mToo low...\033[0m\n";
		elseif ($guess == $number)
			echo "\033[0;32m\nYou guessed it!\033[0m\n";
			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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles