Logical operators help you combine or change true/false conditions in your code. They let you make decisions based on multiple rules.
0
0
Logical operators in PHP
Introduction
Checking if a user is logged in AND has admin rights before showing a page.
Deciding if a number is positive OR zero to allow certain actions.
Making sure a password is long enough AND contains special characters.
Running code only if a file exists AND is readable.
Allowing access if a user is an admin OR a moderator.
Syntax
PHP
$a && $b // AND operator $a || $b // OR operator !$a // NOT operator $a and $b // alternative AND $a or $b // alternative OR $a xor $b // exclusive OR
Use && and || for logical AND and OR with higher precedence.
and and or are similar but have lower precedence, which can affect complex expressions.
Examples
This sets
$x to false because true AND false is false.PHP
$x = true && false; var_dump($x);
This sets
$y to true because true OR false is true.PHP
$y = true || false; var_dump($y);
This sets
$z to true because NOT false is true.PHP
$z = !false; var_dump($z);
This sets
$a to true because exactly one is true (exclusive OR).PHP
$a = true xor false; var_dump($a);
Sample Program
This program checks if a user is logged in and an admin. It prints different messages based on these conditions.
PHP
<?php $is_logged_in = true; $is_admin = false; if ($is_logged_in && $is_admin) { echo "Access granted"; } elseif ($is_logged_in && !$is_admin) { echo "Access limited"; } else { echo "Access denied"; }
OutputSuccess
Important Notes
Remember that && and and are not exactly the same because of operator precedence.
Use parentheses ( ) to make complex conditions clear and avoid mistakes.
Logical operators always return boolean values true or false, except xor which returns true only if exactly one condition is true.
Summary
Logical operators combine true/false values to control program flow.
Use && for AND, || for OR, and ! for NOT.
Be careful with operator precedence and use parentheses to keep conditions clear.