bhylu.com

Advertisements

PHP Logical Operators

A compound condition can avoid an unsafe operation when an earlier condition fails. Write that dependency explicitly instead of relying on an exception to reveal a bad input shape.

How it works

With &&, the right operand is evaluated only when the left is true. With ||, it is evaluated only when the left is false. These rules let a type or existence check protect a later operation. Prefer && and || in ordinary expressions: and and or have different precedence around assignment. Boolean checks should describe facts, not hide state changes inside a difficult-to-trace expression.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l boolean-rules.php
php boolean-rules.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · boolean-rules.php

<?php
declare(strict_types=1);

$input = ["item" => "Spade"];
$isValid = isset($input["item"]) && is_string($input["item"]) && trim($input["item"]) !== "";
echo $isValid ? "Named item\n" : "Missing item\n";
$hasEither = false || true;
echo $hasEither ? "One condition passed\n" : "Neither passed\n";

Expected result

Named item
One condition passed

The string check protects trim from an unexpected array field. The final comparison distinguishes a blank string from a useful name. Short-circuiting is part of the expression’s contract, not an optimisation to depend on accidentally. A real request parser should return clear errors rather than forcing every caller to repeat the same checks.

Check the official PHP manual for detailed version and API contracts.