PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
In PHP, logical operators are used to combine conditional statements.
Here are the logical operators available in PHP:
Here's an example of how to use each one:
$x = 10; $y = 20; // And Operator if ($x == 10 && $y == 20) { echo "True"; // This will output "True" because both conditions are true. } else { echo "False"; } // Or Operator if ($x == 10 || $y == 30) { echo "True"; // This will output "True" because one of the conditions is true. } else { echo "False"; } // Not Operator if (!($x == 20)) { echo "True"; // This will output "True" because $x is not equal to 20. } else { echo "False"; } // Xor Operator if ($x == 10 xor $y == 30) { echo "True"; // This will output "True" because only one of the conditions is true. } else { echo "False"; }
These operators are very useful for controlling the flow of your program based on multiple conditions. Use parentheses to make complex conditions more clear and to control the order in which the conditions are evaluated.
Using AND, OR, and NOT in PHP:
$a = true; $b = false; // AND operator $result_and = $a && $b; // false // OR operator $result_or = $a || $b; // true // NOT operator $result_not = !$a; // false
Combining logical operators in PHP expressions:
$x = 5; $y = 10; // Combined expression $result_combined = ($x > 0 && $y < 15) || ($y == 10); // true
Order of precedence with PHP logical operators:
$a = true; $b = false; $c = true; // Precedence: AND > OR $result_precedence = $a || $b && $c; // true
Short-circuit evaluation in PHP:
$a = true; $b = false; // Short-circuit AND $result_short_and = $a && ($b = true); // $b remains false // Short-circuit OR $result_short_or = $a || ($b = true); // $b becomes true
Boolean values and comparisons in logical expressions:
$num = 10; // Comparison in logical expression $result_comparison = ($num > 5) && ($num < 15); // true
Complex conditions with parentheses in PHP:
$x = 8; $y = 20; // Complex condition $result_complex = ($x > 5 && $y < 15) || ($y == 20); // true
Bitwise logical operators in PHP:
$a = 5; // binary: 0101 $b = 3; // binary: 0011 // Bitwise AND $result_bitwise_and = $a & $b; // 1 (binary: 0001) // Bitwise OR $result_bitwise_or = $a | $b; // 7 (binary: 0111)
Examples of practical usage of PHP logical operators:
Checking user permissions:
$is_admin = true; $can_edit = true; $can_delete = false; $can_manage = ($is_admin && ($can_edit || $can_delete));
Form validation:
$username = "user123"; $password = "pass123"; $is_valid = (strlen($username) >= 6 && strlen($password) >= 8);
Filtering data:
$price = 25; $quantity = 3; $is_discounted = ($price > 20 && $quantity >= 3);