Calculation

Introduction

Use PHP1 to generate two random numbers.
Randomly choose one operation (addition, subtraction, multiplication, division).
Display the numbers and the operation, and ask the user to enter the result.
Check if the user's answer is correct and display the result with PHP2.

Code - PHP1

<?php
	// generate two random numbers
	$number1 = rand(1, 10);
	$number2 = rand(1, 10);

	// randomly choose an operation
	$operation = rand(1, 4);
	if ($operation == 1) {
		$operator = "+";
	} elseif ($operation == 2) {
		$operator = "-";
	} elseif ($operation == 3) {
		$operator = "*";
	} else {
		$operator = "/";
	}

	// display the HTML form
	echo "<form action='index.php' method='post'>";
	echo "$number1 $operator $number2 = ";
	echo "<input type='text' name='answer' />";

	// pass the numbers and operator to PHP2 'in the background'
	echo "<input type='hidden' name='number1' value='$number1' />";
	echo "<input type='hidden' name='number2' value='$number2' />";
	echo "<input type='hidden' name='operator' value='$operator' />";
	echo "<input type='submit' />";
?>

Code - PHP2

<?php
	// receive the numbers and the answer by user
	// store in variables $number1, $number2, $answer
	$number1 = $_POST['number1'];
	$number2 = $_POST['number2'];
	$answer = $_POST['answer'];
	$operator = $_POST['operator'];

	// calculate the correct answer
	if ($operator == "+") {
		$correct = $number1 + $number2;
	} elseif ($operator == "-") {
		$correct = $number1 - $number2;
	} elseif ($operator == "*") {
		$correct = $number1 * $number2;
	} else {
		$correct = $number1 / $number2;
	}	

	// check if the answer is correct
	if ($answer == $correct) {
		echo "Correct!";
	} else {
		echo "Wrong!";
	}
?>

Demo

Open in new window

Task

Fix the above code:
1. Avoid negative results in subtraction.
2. Make sure division result is a whole number.

Reference

Rand - W3SCHOOL.COM.CN
PHP if...else - W3SCHOOLS.COM