Summary - Operators
Combine arithmetic, comparison and logical operators to build a grade calculator.
Bringing operators together
In this group you learned five operator families: arithmetic (+ - * / % **), assignment (= += -= *= /=), comparison (== === != < >), logical (&& || !) and string concatenation (. .=).
The real power is using them together in one program. A grade calculator: find the average with arithmetic, check the threshold with comparison, combine extra conditions with logical, and display the result neatly with concatenation.
Exercise Compute the grade average
Assign to $average the sum of $score1, $score2 and $score3 divided by 3. Then print $average with echo. You must use arithmetic operators.
Show example solution
For the average, write $average = ($score1 + $score2 + $score3) / 3;
Example solution:
<?php
$score1 = 60;
$score2 = 70;
$score3 = 80;
// Compute the average
$average = ($score1 + $score2 + $score3) / 3;
echo $average;
Exercise Print the pass/fail status
Write an if with the condition $average >= 50. When true, print "passed" with echo; otherwise print "failed". You must use an else branch.
Show example solution
For the status, write if ($average >= 50) { ... } else { ... }.
Example solution:
<?php
$average = 70;
// Print the status
if ($average >= 50) {
echo "passed";
} else {
echo "failed";
}
Operator toolkit complete
You now know PHP's core operators. Arithmetic does the math, assignment updates variables, comparison makes decisions, logical combines conditions, and concatenation builds strings.
These five families will appear constantly in the arrays, loops and functions you will learn next. In particular, the habit of using === for strict comparison protects you from unexpected type conversions.
Test yourself
-
$average = 70; var_dump($average >= 50); what is the output?
$average = 70; var_dump($average >= 50);- bool(false)
- int(70)
- bool(true)
- int(50)
Show answer
bool(true) — Correct. 70 >= 50 returns true.
-
Write the pass condition
$average = 70; var_dump($average ____ 50);Show answer
$average = 70; var_dump($average >= 50);