Learn PHP-18 : Logical Operators

Posted: November 14, 2010 in PHP
Tags:

Logical operators are used when we want to combine operations and expressions into a set of logical comparisons. They are usually used in conjuction with “if and “else” statements to lay out the dynamic logic we need in many situations as we advance in our PHP development. We discuss if and else statements in later lessons.

The following table shows their usage and result logic:

Name Usage Result
And $var1 &&
$var2
TRUE if both $var1 and $var2
are TRUE
And $var1 and $var2 TRUE if both $var1 and $var2
are TRUE
Or $var1 or $var2 TRUE if either $var1 or
$var2 is TRUE
Or $var1 || $var2 TRUE if either $var1 or
$var2 is TRUE
Xor $var1 xor $var2 TRUE if either $var1 or
$var2 is TRUE, but not both
Is Not !$var1 TRUE if $var1 is not TRUE

There are two different variations of “and” and “or” operators because they operate at different precedences.

Here we use an if and else statement(discussed in detail later) to use the “&&” logical operator:

<?php
// change these 2 values to see the results if numbers do not match in our expressions
$var1 = 43;
$var2 = 56;

if (($var1 == 43) && ($var2 == 56)) {
echo "Yes, the values produce the match we want.";
} else {
echo "No, the values do not match yet.";
}
?>

The output is shown below :

Yes, the values produce the match we want.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s