INTRODUCTION

Site Home
LAMP Home
PHP Console Home
Getting Started
PHP Reference
Download Tutorial

LESSONS

01 Hello World!
02 Text I/O
03 Arithmetic
04 IF Statement
04 (b) Data Types
05 FOR Loop
06 Functions
07 While Loop
08 Do Loop
09 PHP Reference
10 Array
11 Classes
12 Menu
13 File I/O
14 Factorial N

MORE PHP

PHP in web pages
PHP and MySQL

Task Three - Simple Maths - PHP Tutorial

This program prompts you for two numbers and then adds them together before displaying the answer.

Here is the result of running the program.

Here is the program code.


<?php

// ===== INPUT ==============================
echo "\n\nPlease enter a number ... ";
$N1 = fgets(STDIN);

echo "\n\nPlease enter a number ... ";
$N2 = fgets(STDIN);
// ==========================================

// ===== PROCESS ============================
$output = $N1 + $N2;
// ==========================================

// ===== OUTPUT =============================
echo "\n\nThe answer is $output.\n\n\n";
// ==========================================

?>

 

Code

Explanation

echo "\n\nPlease enter a number ... ";

echo displays the text inside the double quotes. "\n" causes a new line to be started.

$N1 = fgets(STDIN);

fgets() fetches a line of text from the keyboard (until the Enter key is pressed).

$N1 is a variable (pigeon hole) where a number can be stored. (You could type text here but the result would not be useful.)

$N2 = fgets(STDIN);

fgets() fetches a line of text from the keyboard (until the Enter key is pressed).

$N2 is a variable (pigeon hole) where a number can be stored. (You could type text here but the result would not be useful.)

$output = $N1 + $N2;

Then the addition is carried out and the result assigned to $output.

echo "\n\nThe answer is $output.\n\n\n";

echo displays the following

  • two blank lines
  • "The answer is"
  • The data held in $output
  • A period (full stop)
  • Three more blank lines

 

Learning Task

Write more programs to add, subtract, multiply and divide. Try dividing by zero!

Arithmetic Operators

Example Name Result
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.