Explain it simply
Explain it simply
This lesson introduces no new theory; it is a practice lesson. Learning a language is like learning to drive: reading about the road does not make you a driver, but driving it yourself does. This lesson makes you repeat one loop over and over: write the code, run it, read the error when something breaks, and fix it.
For every task, a tiny function called check() decides on your behalf whether the answer is right. It compares what your function returned with the value you expected and prints ok or FAIL. That kind of self-checking is the first step toward the habit of writing tests.
Problem → Why → Solution
The problem: thinking that reading is the same as writing
Reading example code feels familiar. But when you type into an empty file yourself, mistakes appear in places you did not expect. The first attempt below contains two of them. The first is using + instead of . to join strings. In PHP + is an arithmetic operator, so running "Hi, my name is " + $name raises a TypeError: "Unsupported operand types: string + string".
The second is writing = instead of => in foreach ($fruits as $i = $fruit). That is a parse error (syntax error, unexpected token "="): the whole file is rejected before any line runs, so even the first echo never appears. You will not see either of these unless you type the code yourself.
<?php
$name = "Aung";
$age = 22;
echo "Hi, my name is " + $name + " and I am " + $age;
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $i = $fruit) {
echo $i . ". " . $fruit . "\n";
}Why only typing it teaches you
Reading tests recognition, while writing tests recall. A wrong character, a wrong operator or a forgotten edge case only shows up when you recall the code, and reading the error message becomes real experience. Exercises exist so you gain that experience before the bugs reach your users.
Core concept: write, predict, run, compare
There is a fixed routine for working through an exercise, and the same routine applies later when you write a new feature in a real project.
1. Read the task without looking at the solution
Restate it in your own words: what is the input and what is the output? If you cannot, you have not understood the task yet.
2. Write the signature first
Write the parameter types and the return type first, as in function numberedList(array $items): string. That is the function's promise. It forces you to decide clearly what goes in and what comes out, which makes the rest easier.
3. Predict the output
Before running, predict on paper the normal case and the edge cases: an empty array, a single item, a negative number, an array with string keys. A wrong prediction means there is something you do not know yet.
4. Run it with check()
check() compares with ===, so 5 and "5" count as different, which exposes wrong types. The label shows at once which case failed.
5. Read the first error and fix one thing at a time
If several errors appear, read the top one first, because the later ones are often side effects of it. Fix one thing, run again, and only then move on.
| Kind of error | Example | What happens |
|---|---|---|
| Parse error | foreach ($a as $i = $x) | Nothing in the file runs |
| Warning | Reading an array key that does not exist | A message appears and the script continues |
| Exception such as TypeError | "abc" * 2 | The script stops unless it is caught |
Always run through the edge-case list: empty, a single item, zero, negative, the boundary of a limit (does a mark of 60 pass?), a wrong type, duplicates and text in different scripts. An edge case you did not think of in advance will be found by a user later.
- Write the signature first
- Predict the output, edge cases too
- Run it and read the first message
- Fix one thing, run again
Every time the prediction and the result disagree, you have found something to learn, not failed.
General pattern
<?php
function name(type $input): returnType
{
// work out the answer from $input
return $answer;
}
// self-test: compare what you got with what you expected
$got = name($sample);
echo $got === $expected ? 'ok' : 'FAIL';Write the function with types as its promise, call it with a sample input, and compare the result with the expected value using ===.
Reference solutions with a check() helper
The file below holds the check() helper and reference solutions for five basic tasks, followed by one-line check() calls that document behaviour about comparison, floats and Unicode. Do not copy these solutions. Write each task yourself first, then run your own function against these check lines and compare. When every line says ok, you are done.
<?php
declare(strict_types=1);
function check(string $label, mixed $actual, mixed $expected): void
{
$ok = $actual === $expected;
echo ($ok ? 'ok ' : 'FAIL ') . $label;
if (!$ok) {
$got = var_export($actual, true);
$want = var_export($expected, true);
echo " (got $got, expected $want)";
}
echo "\n";
}
// Task 1: join values into a sentence with the dot operator
function introduce(string $name, int $age): string
{
return 'Hi, my name is ' . $name . ' and I am ' . $age . ' years old';
}
// Task 2: a numbered list, however the array is keyed
function numberedList(array $items): string
{
$lines = [];
foreach (array_values($items) as $i => $item) {
$lines[] = ($i + 1) . '. ' . $item;
}
return implode("\n", $lines);
}
// Task 3: even numbers in a range
function isEven(int $n): bool
{
return $n % 2 === 0;
}
function evenNumbers(int $from, int $to): array
{
$result = [];
for ($n = $from; $n <= $to; $n++) {
if (isEven($n)) {
$result[] = $n;
}
}
return $result;
}
// Task 4: a label for odd and even numbers
function parity(int $n): string
{
return isEven($n) ? 'Even' : 'Odd';
}
// Task 5: an average that survives an empty list
function average(array $numbers): ?float
{
if ($numbers === []) {
return null;
}
return array_sum($numbers) / count($numbers);
}
check('introduce', introduce('Aung', 22), 'Hi, my name is Aung and I am 22 years old');
$fruits = ['apple', 'banana', 'mango'];
check('numberedList', numberedList($fruits), "1. apple\n2. banana\n3. mango");
$keyed = ['a' => 'x', 'b' => 'y'];
check('numberedList with string keys', numberedList($keyed), "1. x\n2. y");
check('numberedList empty', numberedList([]), '');
check('evenNumbers 1..10', evenNumbers(1, 10), [2, 4, 6, 8, 10]);
check('evenNumbers -3..3', evenNumbers(-3, 3), [-2, 0, 2]);
check('evenNumbers 10..1', evenNumbers(10, 1), []);
check('parity(7)', parity(7), 'Odd');
check('parity(-3)', parity(-3), 'Odd');
check('-3 % 2 is -1, not 1', -3 % 2, -1);
check('average([2, 4, 9])', average([2, 4, 9]), 5.0);
check('average([])', average([]), null);
// Task 6: loose (==) and strict (===) comparison, floats and Unicode
check('"abc" == 0', 'abc' == 0, false);
check('"1" == "01"', '1' == '01', true);
check('"10" == "1e1"', '10' == '1e1', true);
check('"1" === "01"', '1' === '01', false);
check('null == false', null == false, true);
check('null === false', null === false, false);
check('0.1 + 0.2 === 0.3', 0.1 + 0.2 === 0.3, false);
$word = 'မြန်မာ';
check('bytes and characters', [strlen($word), mb_strlen($word)], [18, 6]);Code breakdown
- A tiny test harness
$ok = $actual === $expected;=== is true only when both value and type match, so 5.0 versus 5 and "5" versus 5 are told apart. That helps you notice changes early.
- Dot, not plus
return 'Hi, my name is ' . $name . ' and I am ' . $age . ' years old';The dot joins strings and converts the int $age to a string automatically. Using + would be arithmetic and raise a TypeError.
- Re-index before numbering
foreach (array_values($items) as $i => $item) {array_values() renumbers the keys as 0, 1, 2, so ($i + 1) also works for an array with string keys like ['a' => 'x']. Note the => and not a single =.
- Modulo and the sign of negatives
return $n % 2 === 0;-3 % 2 is -1, not 1, because the sign of the result follows the left operand. Testing for odd with % 2 === 1 therefore fails for negatives, while testing for even with % 2 === 0 stays correct.
- Guard the empty case
if ($numbers === []) {With an empty array count() is 0, and dividing by 0 raises a DivisionByZeroError. The function checks first and returns null; the ?float return type permits that "no value" answer.
- Floats are not exact
check('0.1 + 0.2 === 0.3', 0.1 + 0.2 === 0.3, false);0.1 + 0.2 is not exactly 0.3. Do not compare floats with ===; check that the difference is below a small tolerance, or store money as cents.
- Bytes versus characters
check('bytes and characters', [strlen($word), mb_strlen($word)], [18, 6]);The Myanmar word "မြန်မာ" is 18 bytes in UTF-8 but only 6 code points. strlen() counts bytes while mb_strlen() counts code points.
ok introduce
ok numberedList
ok numberedList with string keys
ok numberedList empty
ok evenNumbers 1..10
ok evenNumbers -3..3
ok evenNumbers 10..1
ok parity(7)
ok parity(-3)
ok -3 % 2 is -1, not 1
ok average([2, 4, 9])
ok average([])
ok "abc" == 0
ok "1" == "01"
ok "10" == "1e1"
ok "1" === "01"
ok null == false
ok null === false
ok 0.1 + 0.2 === 0.3
ok bytes and charactersLoose and strict comparison in PHP 8
| Expression | Result | Reason |
|---|---|---|
| "abc" == 0 | false | In PHP 8 a number compared with a non-numeric string is compared as strings |
| "1" == "01" | true | Both are numeric strings, so they are compared as numbers |
| "10" == "1e1" | true | 1e1 is the number 10 |
| null == false | true | Both are falsy |
| "0" == false | true | "0" counts as false |
| 0 == "" | false | An empty string is not numeric in PHP 8 |
| [] == false | true | An empty array is falsy |
Every row of this table was checked by running it. The guidance is simple: use === unless you have a specific reason not to. declare(strict_types=1) controls type coercion in function calls only; it does not change how == behaves.
Unicode: bytes, code points and mbstring
Plain string functions such as strlen(), strtoupper() and substr() work on bytes. English letters are one byte each, so nothing goes wrong, but Myanmar letters and accented characters such as é take several bytes in UTF-8. Functions starting with mb_ work on code points. If the mb_ functions are missing, enable PHP's mbstring extension. Even mb_strlen() counts code points, not the letters a reader sees, so for Myanmar text and emoji sequences it is worth reading about the grapheme_ functions of the intl extension.
<?php
$word = 'မြန်မာ';
echo strlen($word) . " bytes\n";
echo mb_strlen($word) . " code points\n";
echo mb_substr($word, 0, 2) . " <- first two code points\n";
echo strtoupper('élan') . ' vs ' . mb_strtoupper('élan') . "\n";18 bytes
6 code points
မြ <- first two code points
éLAN vs ÉLANThe output shows that in the default setup strtoupper() leaves é untouched. So when you change case, count or cut text that a user typed, use the mb_ functions.
Numbers: modulo, integer division and dividing by zero
The sign of a % result follows the left operand: 7 % 3 is 1, -7 % 3 is -1 and 7 % -3 is 1. intdiv() is whole-number division, while 7 / 2 gives 3.5. In PHP 8, dividing by zero (/, % and intdiv() alike) raises a DivisionByZeroError, which means you can catch it.
<?php
// The sign of % follows the left operand.
echo 7 % 3, ' ', -7 % 3, ' ', 7 % -3, "\n";
// intdiv() drops the fraction, / keeps it.
echo intdiv(7, 2), ' ', 7 / 2, "\n";
foreach ([[10, 2], [10, 0]] as [$a, $b]) {
try {
echo "$a / $b = " . ($a / $b) . "\n";
} catch (DivisionByZeroError $e) {
echo "$a / $b failed: " . $e->getMessage() . "\n";
}
}1 -1 1
3 3.5
10 / 2 = 5
10 / 0 failed: Division by zeroIn real projects
In real projects
Here you write check() yourself, but in real projects a tool such as PHPUnit does the same job. PHPUnit's assertSame() compares with ===, so the habit you practise here carries straight over. A good share of the code in any project consists of small functions like these: formatting a name, computing page numbers, working out percentages and cleaning text. If you can write those well, you can build bigger features from them.
Job interviews also ask for code katas such as FizzBuzz, reversing a string or finding duplicates. What those questions really look at is less the correct answer than how you think about edge cases and how you track down a mistake.
Common mistakes
Common mistakes
Using + instead of . to join strings
In JavaScript + also joins strings, but in PHP only the dot does. Running "Hi " + $name gives TypeError: Unsupported operand types: string + string. It is the most common slip for people who come from another language.
Writing = instead of => in foreach
foreach ($items as $i = $item) is a parse error, so the whole file fails to run and even earlier echo lines never appear. When this happens, look at the line number in the message and check that line and the one above it.
Testing for odd with % 2 === 1
Because -3 % 2 is -1, an isOdd written as $n % 2 === 1 reports every negative number as not odd. Test for even with % 2 === 0 and treat everything else as odd.
Comparing floats with ===
0.1 + 0.2 === 0.3 is false. When you check a decimal result, round it first or test that the difference is below a small value such as 0.000001.
Mini challenge
Write three functions and test them with check()
Write three functions. initials() takes a full name and returns the first letter of each word in upper case. clamp() keeps a value between a min and a max. fizzBuzz() returns the list from 1 up to the given number. Use the check() helper from the lesson to test your own work.
- initials() ignores extra spaces, returns an empty string for an empty string, and also works with accented letters such as é
- clamp() throws InvalidArgumentException when min > max
- fizzBuzz() gives Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both, and the number as a string otherwise
- fizzBuzz(0) returns an empty array
<?php
declare(strict_types=1);
// Reuse check($label, $actual, $expected) from the lesson.
function initials(string $fullName): string
{
// TODO: first letter of every word, upper-case, ignoring extra spaces
}
function clamp(int $value, int $min, int $max): int
{
// TODO: keep $value between $min and $max; throw if $min > $max
}
function fizzBuzz(int $upTo): array
{
// TODO: 1..$upTo as strings, with Fizz, Buzz and FizzBuzz where they belong
}
check('initials', initials('Aung Kyaw Moe'), 'AKM');
check('clamp', clamp(15, 1, 10), 10);
check('fizzBuzz(5)', fizzBuzz(5), ['1', '2', 'Fizz', '4', 'Buzz']);Expected: Eleven lines appear: four for initials, four for clamp and three for fizzBuzz, and all of them must say ok with no FAIL.
Show hint
explode(' ', $name) splits on spaces, but doubled spaces leave empty strings in the result, so remove them with array_filter. Use mb_substr($word, 0, 1) and mb_strtoupper() for the first letter. In FizzBuzz, test the multiples of 15 first.
Show solution
<?php
declare(strict_types=1);
function check(string $label, mixed $actual, mixed $expected): void
{
$verdict = $actual === $expected ? 'ok ' : 'FAIL';
echo "$verdict $label\n";
}
function initials(string $fullName): string
{
$words = array_filter(explode(' ', $fullName), fn (string $w) => $w !== '');
$letters = array_map(fn (string $w) => mb_strtoupper(mb_substr($w, 0, 1)), $words);
return implode('', $letters);
}
function clamp(int $value, int $min, int $max): int
{
if ($min > $max) {
throw new InvalidArgumentException('min must not be greater than max');
}
return max($min, min($max, $value));
}
function fizzBuzz(int $upTo): array
{
$out = [];
for ($n = 1; $n <= $upTo; $n++) {
if ($n % 15 === 0) {
$out[] = 'FizzBuzz';
} elseif ($n % 3 === 0) {
$out[] = 'Fizz';
} elseif ($n % 5 === 0) {
$out[] = 'Buzz';
} else {
$out[] = (string) $n;
}
}
return $out;
}
check('initials', initials('Aung Kyaw Moe'), 'AKM');
check('initials with extra spaces', initials(' su mya '), 'SM');
check('initials of an accented name', initials('émile zola'), 'ÉZ');
check('initials of an empty string', initials(''), '');
check('clamp inside the range', clamp(5, 1, 10), 5);
check('clamp below the range', clamp(-4, 1, 10), 1);
check('clamp above the range', clamp(15, 1, 10), 10);
try {
clamp(1, 5, 2);
$message = 'no exception';
} catch (InvalidArgumentException $e) {
$message = $e->getMessage();
}
check('clamp with min > max', $message, 'min must not be greater than max');
check('fizzBuzz(5)', fizzBuzz(5), ['1', '2', 'Fizz', '4', 'Buzz']);
check('fizzBuzz(0)', fizzBuzz(0), []);
check('fizzBuzz ends with FizzBuzz', array_slice(fizzBuzz(15), -1), ['FizzBuzz']);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Work through each exercise by writing from the signature, predicting, running and comparing; a check() helper that uses === is useful
- + is arithmetic and . joins strings, foreach needs =>, and the sign of % follows the left operand
- Use === unless there is a reason not to, never compare floats with ===, and use mb_ functions for user text
- A parse error stops the whole file while a warning does not stop the script; read the first error first
PHP Language Reference — PHP Documentation Group