exercises and solutions

Types/comparison exercises

Types and comparison exercises should expose PHP's boundary between submitted strings and application values. They are useful revision for strict comparisons, validation, casting, truthiness, and false-like return values.

Practical Example

PHP example
<?php

declare(strict_types=1);

$submittedAge = '18';
$age = filter_var($submittedAge, FILTER_VALIDATE_INT);

echo ($age === 18 ? 'Adult' : 'Check age') . PHP_EOL;

// Prints:
// Adult

Type and comparison exercises should make learners practise strict comparison, casting, validation, and the difference between strings that look numeric and real integers.

Require === where type matters. Include values such as '0', 0, false, null, and an invalid numeric string so loose comparison mistakes become visible.

Practice

Validate A Submitted Quantity

Validate submitted values '3', '0', and 'three' as positive integer quantities. Print accepted integers and a clear rejection for the others.

Show solution

Use filter_var($value, FILTER_VALIDATE_INT) and compare the result strictly with false. Then apply the domain rule $quantity >= 1.

'3' becomes integer 3. '0' is an integer but fails the positive-quantity rule. 'three' fails validation.

Find A Strict Match

Search [0, "0", false, null] for integer 0. Use strict comparison and explain why a loose lookup would make the result unreliable.

Show solution

Use array_search(0, $values, true) and compare the returned key with === false. The strict flag prevents "0" and false from being treated as the integer 0, while the explicit failure comparison preserves key 0 as a valid match.