PHP - Operator Logical Operators

Introduction

PHP's logical operators work on Boolean values.

A Boolean value is either true or false.

PHP automatically evaluates expressions as either true or false when needed.

For example, the following expressions all evaluate to true :

1
1 == 1
3  >  2
"hello" != "goodbye"

The following expressions all evaluate to false :

3  <  2
gettype( 3 ) == "array"
"hello" == "goodbye"

In addition, PHP considers the following values to be false :

  • The literal value false
  • The integer zero ( 0 )
  • The float zero (0.0 )
  • An empty string ( " " )
  • The string zero ( "0" )
  • An array with zero elements
  • The special type null (including any unset variables)
  • A SimpleXML object that is created from an empty XML tag

All other values are considered true in a Boolean context.

You can combine Boolean values with logical operators.

PHP features six logical operators.

They work with true or false Boolean values to produce a result of either true or false:

Operator Example Result
&& (and) $x && $y true if both $x and $y evaluate to true ; false otherwise
and $x and $ytrue if both $x and $y evaluate to true ; false otherwise
|| (or) $x || $y true if either $x or $y evaluates to true ; false otherwise
or $x or $y true if either $x or $y evaluates to true ; false otherwise
xor $x xor $ytrue if $x or $y (but not both) evaluates to true ; false otherwise
! (not) !$x true if $x is false ; false if $x is true

Here are some simple examples of logical operators in action:

Demo

<?php

$x = 2;/*from ww w .ja v a 2 s. c  o  m*/
$y = 3;
echo ( ($x  >  1)  &&  ($x  <  5) ) .  "  \n ";    // Displays 1 (true)
echo ( ($x == 2) or ($y == 0) ) . " \n ";  // Displays 1 (true)
echo ( ($x == 2) xor ($y == 3) ) . " \n "; // Displays "" (false) because both expressions are true
echo ( !($x == 5 ) ) . " \n ";             // Displays 1 (true) because $x does not equal 5
?>

Result

Related Topics