Core PHP 8 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Use arithmetic, assignment, comparison, logical, increment/decrement and string operators.
  • Tell the difference between == and ===.
  • Use combined operators such as += and .=.
  • Apply operator precedence and associativity, and override them with parentheses.
  • Use the modern operators ??, <=> and **.
Expressions and Operators

In PHP there are two kinds of "expressions" you will hear about. One is the regular expression, used to manipulate text (Chapter 12). The other is more mathematical – it describes operations to be performed on values and variables:

$c = $a + $b;

Assuming $a and $b are numbers, this expression adds them and stores the sum in $c (the = sign makes it an assignment). In $a + $b the plus sign is an arithmetic operator; $a and $b are its operands.

Arithmetic Operators
OperatorSymbolExampleResult ($a = 17, $b = 5)
Addition+$a + $b22
Subtraction-$a - $b12
Multiplication*$a * $b85
Division/$a / $b3.4
Modulus (remainder)%$a % $b2
Exponentiation**$a ** 2289
Negation--$a-17
File: htdocs/phpbook/ch05/arith.php
<?php
$a = 17;
$b = 5;
echo "a + b = " . ($a + $b) . "<br>";
echo "a - b = " . ($a - $b) . "<br>";
echo "a * b = " . ($a * $b) . "<br>";
echo "a / b = " . ($a / $b) . "<br>";
echo "a % b = " . ($a % $b) . "<br>";
echo "a ** 2 = " . ($a ** 2) . "<br>";
echo "intdiv(a, b) = " . intdiv($a, $b);
?>
OUTPUT browser · http://localhost/phpbook/ch05/arith.php
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a % b = 2
a ** 2 = 289
intdiv(a, b) = 3
Comparison Operators

A comparison returns a boolean – true or false.

OperatorSymbolTrue when …
Equal==values are equal after type juggling
Identical===values are equal and of the same data type
Not equal!= or <>values are not equal
Not identical!==values differ or the types differ
Less than<left is smaller
Greater than>left is bigger
Less than or equal to<=left is smaller or equal
Greater than or equal to>=left is bigger or equal
Spaceship<=>returns -1, 0 or 1 (less, equal, greater)
File: htdocs/phpbook/ch05/compare.php
<?php
$x = 5;       // integer
$y = "5";     // string
echo "<pre>";
echo '$x == $y  : '; var_dump($x == $y);
echo '$x === $y : '; var_dump($x === $y);
echo '$x != 8   : '; var_dump($x != 8);
echo '$x !== $y : '; var_dump($x !== $y);
echo '$x >= 5   : '; var_dump($x >= 5);
echo '3 <=> 7   : '; var_dump(3 <=> 7);
echo '7 <=> 7   : '; var_dump(7 <=> 7);
echo "</pre>";
?>
OUTPUT browser · http://localhost/phpbook/ch05/compare.php
$x == $y  : bool(true)
$x === $y : bool(false)
$x != 8   : bool(true)
$x !== $y : bool(true)
$x >= 5   : bool(true)
3 <=> 7   : int(-1)
7 <=> 7   : int(0)

Prefer === and !== when you compare values that may be of different types, such as the result of strpos() (which can return 0 or false). PHP 8 also made 0 == "abc" false (in PHP 7 it was true), which removed a classic source of bugs.

Logical Operators
OperatorSymbolResult
And&& or andtrue if both operands are true
Or|| or ortrue if at least one operand is true
Xorxortrue if only one of the two is true
Not!true if the operand is false
File: htdocs/phpbook/ch05/logical.php
<?php
$age = 20;
$hasId = true;
echo "<pre>";
echo "age >= 18 && hasId : "; var_dump($age >= 18 && $hasId);
echo "age < 18 || hasId  : "; var_dump($age < 18 || $hasId);
echo "true xor true      : "; var_dump(true xor true);
echo "!hasId             : "; var_dump(!$hasId);
echo "</pre>";
?>
OUTPUT browser · http://localhost/phpbook/ch05/logical.php
age >= 18 && hasId : bool(true)
age < 18 || hasId  : bool(true)
true xor true      : bool(false)
!hasId             : bool(false)
Increment and Decrement Operators
OperatorExampleMeaning
Pre-increment++$vadd 1, then return the new value
Post-increment$v++return the current value, then add 1
Pre-decrement--$vsubtract 1, then return the new value
Post-decrement$v--return the current value, then subtract 1
File: htdocs/phpbook/ch05/incdec.php
<?php
$v = 5;
echo "v++ gives " . $v++ . ", now v = $v<br>";
echo "++v gives " . ++$v . ", now v = $v<br>";
echo "v-- gives " . $v-- . ", now v = $v<br>";
echo "--v gives " . --$v . ", now v = $v";
?>
OUTPUT browser · http://localhost/phpbook/ch05/incdec.php
v++ gives 5, now v = 6
++v gives 7, now v = 7
v-- gives 7, now v = 6
--v gives 5, now v = 5
The Concatenation Operator

The concatenation "operator" is a period (full stop). It simply says "join this to this":

File: htdocs/phpbook/ch05/concat.php
<?php
$parta = "This is part one";
$partb = " of a sentence!";
print $parta . $partb;
echo "<br>";
$msg = "PHP";
$msg .= " and MySQLi";   // .= appends to the variable
echo $msg;
?>
OUTPUT browser · http://localhost/phpbook/ch05/concat.php
This is part one of a sentence!
PHP and MySQLi
Combined (Assignment) Operators

= is the assignment operator: $a = 5 assigns the value 5 to $a. It can be combined with other operators. If $a is 5, then after $a += 5 it is 10 – exactly as if you had written $a = $a + 5. Some programmers like combined operators because they reduce typing; use whichever form you find clearer.

OperatorExampleSame as
+=$d1 += 3$d1 = $d1 + 3
-=$d1 -= 3$d1 = $d1 - 3
*=$d1 *= 3$d1 = $d1 * 3
/=$d1 /= 3$d1 = $d1 / 3
%=$d1 %= 3$d1 = $d1 % 3
.=$s .= "x"$s = $s . "x"
??=$n ??= 1$n = $n ?? 1
File: htdocs/phpbook/ch05/combined.php
<?php
$d1 = 12;
$d1 += 3; echo "After += 3 : $d1<br>";
$d1 -= 5; echo "After -= 5 : $d1<br>";
$d1 *= 2; echo "After *= 2 : $d1<br>";
$d1 /= 4; echo "After /= 4 : $d1<br>";
$d1 %= 3; echo "After %= 3 : $d1";
?>
OUTPUT browser · http://localhost/phpbook/ch05/combined.php
After += 3 : 15
After -= 5 : 10
After *= 2 : 20
After /= 4 : 5
After %= 3 : 2
Other Useful Operators
  • Ternary ?: – $result = (condition) ? value_if_true : value_if_false;
  • Null coalescing ?? (PHP 7) – $name = $_GET['name'] ?? 'Guest'; gives the left value if it exists and is not null, otherwise the right value. Very handy for reading form fields.
  • Error control @ – suppresses error messages of an expression (use rarely).
File: htdocs/phpbook/ch05/ternary.php
<?php
$marks = 72;
echo "Result: " . ($marks >= 40 ? "Pass" : "Fail") . "<br>";
$name = $_GET['name'] ?? 'Guest';
$city = $_GET['city'] ?? 'Unknown';
echo "Name: $name, City: $city";
?>
OUTPUT browser · http://localhost/phpbook/ch05/ternary.php?name=Ravi
Result: Pass
Name: Ravi, City: Unknown
Precedence and Associativity

Think about this operation: $a = 7 - 4 + 1. If the minus happens before the plus, the result is 4; if the plus happens first, the result is 2. Since predictability is essential, an order of precedence was established, together with associativity.

  • Precedence gives each operator a rank: operators with higher rank are evaluated first.
  • When several operators have the same rank, associativity decides: left-associative operators are processed from left to right, right-associative operators from right to left. Some operators, such as the comparison operators, are non-associative.

The order of precedence of the operators in this chapter, from highest to lowest (operators on one line have equal precedence):

RankOperators
1**
2++ -- (int) (float) (string) (bool) @
3!
4* / %
5+ -
6. (concatenation – lower than + and - since PHP 8)
7< <= > >=
8== != === !== <> <=>
9&&
10||
11??
12? : (ternary)
13= += -= *= /= .= %= ??=
14and
15xor
16or

You can override precedence with parentheses – the innermost parentheses are processed first:

File: htdocs/phpbook/ch05/precedence.php
<?php
echo "7 - 4 + 1 = " . (7 - 4 + 1) . "<br>";
echo "(7 - 4) + 1 = " . ((7 - 4) + 1) . "<br>";
echo "7 - (4 + 1) = " . (7 - (4 + 1)) . "<br>";
echo "2 + 3 * 3 = " . (2 + 3 * 3) . "<br>";
echo "2 + (3 * 3) = " . (2 + (3 * 3)) . "<br>";
echo "(2 + 3) * 3 = " . ((2 + 3) * 3) . "<br>";
echo "1 + 3 + 3 * 2 = " . (1 + 3 + 3 * 2) . "<br>";
echo "1 + ((3 + 3) * 2) = " . (1 + ((3 + 3) * 2)) . "<br>";
echo "(1 + (3 + 3)) * 2 = " . ((1 + (3 + 3)) * 2);
?>
OUTPUT browser · http://localhost/phpbook/ch05/precedence.php
7 - 4 + 1 = 4
(7 - 4) + 1 = 4
7 - (4 + 1) = 2
2 + 3 * 3 = 11
2 + (3 * 3) = 11
(2 + 3) * 3 = 15
1 + 3 + 3 * 2 = 10
1 + ((3 + 3) * 2) = 13
(1 + (3 + 3)) * 2 = 14
Good habit

Use parentheses whenever you write a complex expression. It makes the code easier to read when you come back to it months or years later – and it never changes a correct result.

Key Takeaways
  • Arithmetic: + - * / % **; comparison: == === != !== < > <= >= <=>; logical: && || xor !.
  • == compares values after conversion; === also compares the data type.
  • $v++ returns the old value, ++$v the new value.
  • The dot . joins strings; .= appends.
  • Combined operators such as += are shorthand for $a = $a + ….
  • ?? supplies a default for missing values; ?: chooses between two values.
  • Precedence and associativity decide evaluation order; parentheses override them.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch05 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : An operator is a symbol that performs an operation, such as + or ==. The values or variables it works on are its operands; in $a + $b, $a and $b are operands.

Answer : + addition, - subtraction, * multiplication, / division, % modulus (remainder) and ** exponentiation; unary - negates a value.

Answer : 2, because % returns the remainder of the integer division: 17 = 3 × 5 + 2.

Answer : == (equal) compares values after type juggling, so 5 == "5" is true. === (identical) is true only when the values are equal and of the same type, so 5 === "5" is false.

Answer : $a <=> $b returns -1 if $a is less than $b, 0 if they are equal and 1 if $a is greater. It is useful in sorting callbacks.

Answer : && (and) is true when both operands are true; || (or) when at least one is true; xor when exactly one is true; ! (not) reverses true and false.

Answer : ++$v adds 1 first and returns the new value; $v++ returns the current value and then adds 1. With $v = 5, echo $v++ prints 5 and echo ++$v prints the incremented value.

Answer : The concatenation operator, a period (.), e.g. "PHP" . " 8" gives "PHP 8". The .= operator appends to an existing string variable.

Answer : Operators that combine an operation with assignment: $a += 5 means $a = $a + 5; similarly -=, *=, /=, %= and .=.

Answer : A shorthand if-else expression: condition ? value_if_true : value_if_false. Example: $r = ($marks >= 40) ? "Pass" : "Fail";

Answer : ?? returns its left operand if it exists and is not null, otherwise its right operand. $name = $_GET['name'] ?? 'Guest'; avoids warnings for missing form fields.

Answer : The rank that decides which operator is evaluated first in an expression without parentheses; e.g. * has higher precedence than +, so 2 + 3 * 3 = 11.

Answer : The rule for evaluating operators of equal precedence. Left-associative operators (like + and -) are evaluated left to right, so 7 - 4 + 1 = 4; right-associative ones (like = and **) are evaluated right to left.

Answer : (1 + (3 + 3)) * 2 = 7 × 2 = 14. 1 + 3 + 3 * 2 = 1 + 3 + 6 = 10.

Answer : They make the intended order of evaluation obvious to anyone reading the code and protect against precedence mistakes, without changing correct results.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. What is the value of 2 + 3 * 3?

Show Answer

Correct Answer : B. 11
* has higher precedence than +, so 3 * 3 = 9 is computed first.

Q2. 5 === "5" evaluates to:

Show Answer

Correct Answer : B. false
=== also compares types; int and string differ.

Q3. If $v = 5, what does echo $v++; print?

Show Answer

Correct Answer : B. 5
Post-increment returns the old value, then increments.

Q4. Which operator appends a string to a variable?

Show Answer

Correct Answer : C. .=
.= is the concatenating assignment operator.

Q5. $name = $_GET['name'] ?? 'Guest'; uses the:

Show Answer

Correct Answer : B. Null coalescing operator
?? returns the right value when the left one is missing or null.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – Operators. https://www.php.net/manual/en/language.operators.php
  2. The PHP Group. (n.d.). PHP Manual – Operator Precedence. https://www.php.net/manual/en/language.operators.precedence.php
  3. The PHP Group. (n.d.). PHP Manual – Comparison Operators. https://www.php.net/manual/en/language.operators.comparison.php
  4. The PHP Group. (n.d.). PHP Manual – Backward incompatible changes (PHP 8.0). https://www.php.net/manual/en/migration80.incompatible.php