|
| HOW TO USE LOGICAL OPERATORS IN PHP
In PHP, logical operators are used to make multiple comparisons. These are the most important ones: and, &&, or, ||, !, xor. Their functions are explained further below:
and
Is true only if both comparisons are true.
Example:
if($num > 0 and $name=='John)
{
echo "Hello";
}
The above code will only echo Hello only if both conditions are true ie. if $num is greater than 0 AND if $name is John.
&&
Similar to and above except it binds it's arguments more tighter, takes precedence over and.
or
Is true only if either comparison is true.
Example:
if($firstName=='John' or $firstName=='Mary')
{
echo "Hello";
}
The above code will only echo Hello if either conditions are true ie. if $firstName is John OR $firstName Mary.
||
Similar to or above except it binds it's arguments more tighter, takes precedence over or.
!
Is true if comparison is false.
Example:
if($firstName !='John')
{
echo "Hello";
}
The above code will only echo Hello if $firstName is NOT John.
xor
Is true if either value is true, but not both.
Example:
if($firstName =='John' xor $lastName =='Smith' )
{
echo "Hello";
}
The above code will only echo Hello if either $firstName is John or $lastName is Smith but not if both $firstName is John and $lastName is Smith .
|
|