PHP — Comparisons and short-circuit operators
PHP's && evaluates the right operand only when its left operand is true. Combine range and value checks to avoid reading an undefined array key.
A simple example
Test two conditions
- Start with n is 2
- Do this Greater than 0 and less than 3?
- Result yes
<?php
$n = 2;
if ($n > 0 && $n < 3) {
echo "yes", PHP_EOL;
}
yes
Operator examples
| Operation | Expression | Result |
|---|---|---|
| Integer division | intdiv(7, 2) |
3 |
| Division | 7 / 2 |
3.5 |
| Remainder | 7 % 2 |
1 |
| Comparison | 5 >= 5 |
true |
| Strict equality | 3 === '3' |
false |
| Logical conjunction | true && false |
false |
Guard an indexed lookup
Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. This array is a dense, zero-based list. For a sparse or associative array use array_key_exists or an appropriate membership check because count alone does not establish a key's presence.
A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.
Run the example
Use PHP 8.2 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
$stock = [2, 5];
foreach ([-1, 1, 2] as $index) {
$take = $index >= 0 && $index < count($stock) && $stock[$index] >= 5;
echo ($take ? 'take' : 'skip') . "\n";
}
skip take skip
Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.
Try it yourself
Try index 0, then change its value from 2 to 5. How does its classification change?
Check your answer
Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.