Logical Operators

Combine conditions with and, or and not.

Syntaxif ($a > 0 && $b > 0) { ... }

Logical operators combine boolean expressions:

  • && (and) — true if both sides are true.
  • || (or) — true if at least one side is true.
  • ! (not) — reverses a boolean.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Combine an email format check and a domain allowlist check with && before activating an account.
  • Use || to provide a fallback language code when the user's preferred locale is unavailable.
  • Negate a permission check with ! to redirect unauthorized users away from an admin route.

More examples

AND and OR conditions

&& requires both conditions to be true; || requires at least one — the building blocks of access-control logic.

Example · php
<?php
$age      = 25;
$hasId    = true;
$isMember = false;

if ($age >= 18 && $hasId) {
    echo 'Entry allowed';
}
if ($isMember || $age >= 65) {
    echo 'Discount applied';
}

Short-circuit evaluation

PHP short-circuits: with &&, if the left side is false the right side is never evaluated, avoiding unnecessary work.

Example · php
<?php
function isActive(int $id): bool {
    echo "Checking $id... ";
    return $id === 1;
}

// Second call never runs when first returns false
if (isActive(2) && isActive(1)) {
    echo 'Both active';
}

NOT operator and double negation

! inverts a boolean; double negation (!!) is an idiomatic way to cast any truthy/falsy value to a strict bool.

Example · php
<?php
$isAdmin = false;

if (!$isAdmin) {
    header('Location: /login');
    exit;
}

// Double negation casts to bool
$hasItems = !!count([1, 2, 3]); // true
var_dump($hasItems);

Discussion

  • Be the first to comment on this lesson.