Avoid Logical Operators

ID

php.avoid_logical_operators

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

reliability, suspicious-comparison

Description

Reports the wordy logical operators and, or and xor, recommending the symbol forms && and || instead. The symbol operators &&, || and ! are never flagged.

Rationale

PHP has two sets of boolean operators with different precedence. The keyword forms and, or and xor bind looser than the assignment operator =, while && and || bind tighter. That difference is a classic bug: $ok = compute() or die(); parses as ($ok = compute()) or die();, so $ok is assigned the raw return value and the die() guard never protects the assignment the way the author expected. Sticking to && / || keeps the precedence intuitive and avoids the trap.

<?php
function connect($dsn): bool
{
    $ok = open($dsn) or fail();   // FLAW — parses as ($ok = open($dsn)) or fail()

    return $ok && ready();        // OK — symbol form binds as expected
}

Remediation

Replace and with && and or with ||. For xor, use an explicit boolean expression such as ($a xor $b) written with comparisons or (bool) $a !== (bool) $b. When relying on a side effect after an operation, use an explicit if statement instead of the low-precedence or idiom.