PHP / CHAPTER 01
Values and explicit comparison
BeginnerAvoid accidental coercion at data boundaries in PHP 8.
By the end of this chapter
- Distinguish strict and loose comparisons
- Use concatenation separately from arithmetic
- Choose null defaults deliberately
The idea
PHP variables begin with a dollar sign and can hold values of different types. This course uses PHP 8 syntax. Text, numbers, booleans, arrays, and null have different meanings, even when printed output looks similar. The dot operator concatenates text, while arithmetic operators perform numeric work. Use strict comparison when both the value and its type are part of the rule.
Input from a request or text file often needs validation before conversion. Loose comparison may coerce operands, so it is a poor substitute for a documented parsing policy. Null coalescing provides a fallback for a missing or null value without discarding zero or false. Make those boundary choices explicit, then keep internal operations focused on already understood values rather than repeatedly guessing their types.
<?php
$count = 0;
echo ($count ?? 10), "
";
echo ("5" === 5 ? "same" : "different"), "
";0 different
Null coalescing preserves zero. Strict comparison rejects equality between a string and an integer even when their printed forms match.
Try it yourself
Return a default title only for null, preserving an explicitly supplied empty string.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING