Computing the operation
Use if/elseif to select the operator and compute the result.
Arithmetic operators
PHP has four basic arithmetic operators:
+addition-subtraction*multiplication/division
Used between two variables, they perform the operation and return the result. For example, $first + $second adds the two numbers. Adding two integers gives an integer; division may give a float. We'll use these operators inside an if/elseif structure.
The if/elseif structure
The if/elseif structure runs different code blocks based on a variable's value. It's ideal for picking the right operation based on the operator.
if ($operator === "+") {
$result = $first + $second;
} elseif ($operator === "-") {
$result = $first - $second;
}The === operator checks that both value and type match. The matching branch runs; if none matches, no block runs.
Exercise Compute the operation with if/elseif
Use an if/elseif structure to compute based on the operator: addition for +, subtraction for -, multiplication for *, division for /. Assign the result to $result and print it with a "Result: " label.
Show example solution
Write a separate if/elseif branch for each operator.
Example solution:
<?php
// The first number entered by the user
$first = 25;
// The chosen operator and second number
$operator = "+";
$second = 4;
$result = 0;
if ($operator === "+") {
$result = $first + $second;
} elseif ($operator === "-") {
$result = $first - $second;
} elseif ($operator === "*") {
$result = $first * $second;
} elseif ($operator === "/") {
$result = $first / $second;
}
echo "Result: " . $result;
Test yourself
-
What is the result of 25 + 4?
<?php $first = 25; $second = 4; echo $first + $second;- 21
- 100
- 29
- 29.0
Show answer
29 — 25 + 4 = 29. PHP int + int gives an int.
-
Type-safe comparison in the if condition
<?php if ($operator ____ "+") { $result = $first + $second; } ?>Show answer
<?php if ($operator === "+") { $result = $first + $second; } ?> -
Match each operator to its operation
- +
- Addition
- -
- Subtraction
- *
- Multiplication
- /
- Division