PHP – Lesson 08: Logical Expressions

Lecture :: Logical Expressions and Operators

Conditional Statements
“==” testing
Less than, Greater than, Etc.
Testing Multiple Conditions at Once
The “switch” Statement
The “?:” Ternary Operator 

Conditional Statements


The great thing about PHP is that it can execute code based on whether or not certain conditions exist within parameters you set. This is what makes the language dynamic: that it can change on the fly based on conditions provided by the programmer, the computer environment (i.e. time of day, browser type….), or the user (i.e. the data they input or select in your forms). Below is a lay version of how a basic “if” conditional statement would look in plain English:

  • If it is 8am, then my alarm clock will buzz.
  • In PHP, it would look like this:
    if (it is 8am) {
    //alarm clock buzzes;

Here’s what it is doing (In plain English):

  • if (condition is met) {
    /*code to be executed goes here;*/

Okay, so what if we want an alternate thing to happen if the condition is NOT met? We use an if…else statement, as follows:

  • if (condition is met) {
    /*code to be executed if condition is met;*/
    } else {
    /* code to be executed if condition is NOT met;*/

Okay, so what if you want more than one option? Let’s say you might encounter several conditions that you want to deal with differently should they arise. You could do it like this:

  • if (condition#1 is met) {
    /*code to be executed if condition#1 is met;*/
    } elseif (condition#2 is met) {
    /* code to be executed if condition#1 is NOT met but condition#2 IS met;*/
    } else {
    /*default code to run if neither condition#1 or condition#2 is met;*/

Okay, let’s look at a real, very simple example. Let’s say that you want to make absolutely sure that a variable has been declared and set before moving on in your script. An example of this would be if a user tries to bypass a page that sets a username (a login page), by going straight to a page only visible to registered users. Here’s an overly-simplified example of how you could check that the $username variable had been declared:

  • if (isset($username)) {
    echo "Hello {$username}.";
    } else {
    echo "Error: you must login before continuing.";

Back to top

Making comparisons with “==

So that was easy enough, but you need to know how to make comparisons in order to test a larger variety of conditions . The most basic is to test equality of either numbers or strings, which is performed with two equal signs “==” as follows:

  • if ($username == 'admin') {
    } else {

IMPORTANT! The double equal signs are not the same as one equal sign. “==” compares two values and tests that they are the same, whereas “=” declares the value of a variable! So, the line if ($username == 'admin'){ says “If the username variable is set to the value of admin, then….” Where the mistake of if ($username = 'admin'){ says “If we declare the username as admin, and we DO declare it so right now, then….” What a huge mistake! You are now opening up your site’s administrative control panel up to everyone.

The opposite of being equal is obviously “not equal.” The way to represent this is by putting a “bang” symbol in front of the equal symbol, like this:

  • !=
  • thus to say 2 is not equal to 3, you would say “2 != 3“, or in variable terms: $a != $b;

Okay, so that is how you indicate that something is not the same as something else. But there is also another equality distinction: to determine if a variable is IDENTICAL to another value. Being identical means that it not only has to be the same value, but it also has to be the same type of data. It checks to see that a variable integer is the same as another another variable integer, or a floating point variable is the same as another floating point value. Here are the representations:

  • === means identical, as in $a === $b;
  • !== means not identical, as in $a !== $c;

This, in effect, is testing the type casting of data, which we have previously discussed. Let’s look at an example and figure out how the test will evaluate:

$a = "2"; // string
$b = 2; // integer

if ($a === $b) {
echo "Identical data";
} else {
echo "Not identical data";

Because $a is a string up above and $b is an integer, the condition will NOT evaluate as true, so it will move to the “else” command.

Back to top

Making comparisons with “>, <, >=, <=

Not everything you compare will be in terms of absolute equality. You can use the “greater-than” and “less-than” range of symbols to compare numbers. Let’s say you have a shopping cart and want to let people know that they are receiving free shipping because they’ve spent more that $100….

  • if ($subtotal >= 100) {
    echo "Your shipping is free!";
    } else {
    echo "Purchase at least $100 of goods and receive free shipping!";

More on Comparison Operators

To learn more about all PHP comparison operators, see the comparison operators page.

Testing multiple conditions at once

To test more than one condition at once, you need to use logical operators. This is the equivalent of saying “test this AND that”, “test this OR that”, and also “test if not something”. Here are the symbols used:

&& is the “AND” logical operator. All all conditions must be met.

|| is the “OR” logical operator. One OR another condition must be met.

! is the negation operator. Tests if a condition is NOT true to fulfill condition.

Here are some examples:

  • if (($username == 'admin') && ($password == true)) {
    /*execute some special administrator login code*/ here;
    } elseif ((!$password)) || (!$username)) {
    echo "Either your username or password was left blank.";
    } elseif ((($user == true) && ($user != 'admin')) && ($password == true)) {
    /*execute some normal user login code;*/

What this is saying, line by line is:

  • if ((the user is ‘admin) AND (a password is entered)) {
    otherwise, if ((there is no username entered) OR (no password is entered)) {
    otherwise if (((there is a username entered) AND (it is something other than the admin user)) AND (a password was entered)) {

Of course, you would have to do more security checks than this in the execution code to make sure the user is a registered user with a correct password, but you can hopefully use this example to understand logical operators.

Back to top

Using the “switch” statement instead of “if/else”

If you have a lot of if/else conditions, the “switch” statement can be more efficient and cleaner. It looks like this (although you’d typically have many more case conditions):

  • switch($variable_being_tested) {
    case value1:
    //statements to be executed;
    case value2:
    //statements to be executed;
    //statements to be executed;

So let’s say you have an array of fruit and the user had to select a type of fruit, and we put the result into a variable called $choice. Now you need to test the user’s $choice to see what the price will be:

  • switch($choice) {
    case 'apple':
    echo "{$choice} is 33 cents.";
    case 'orange':
    echo "{$choice} is 30 cents.";
    echo "Please select a type of fruit.";

Here are critical things to note about “switch” statements:

  • The expression following case must be a number or string.
  • You cannot use comparison operators (eg. <)
  • Each block of code execution statements should end with break; .
  • You can group several case keywords together to execute the same code if necessary.
  • If no match is made to the case conditions, the default code is executed. The default serves as the “else” statement.

Back to top

Using the conditional ternary operator ? :

This is a shorthand way of making a simple conditional statement. Basic example:

  • condition ? value if true : value if false;

Let’s look at something real to help us understand:

  • $liquor_status = $age > 20 ? 'legal' : 'under-age';

This is the same as saying:

  • if ($age > 20) {
    $liquor_status = 'legal';
    } else {
    $liquor_status = 'under-age';

Both are saying, “if the $age variable is greater than 20, it’s legal to buy liquor, but if the $age is 20 or lower, then the customer is under-aged for buying liquor.”

Back to top

“If” Statement Demo (14:59)

If/Else Logical Operators and Functions (14:55)

Setting Multiple Conditions with If-Elseif Statements (14:07)

Using the Basic “Switch” Statement (06:52)


‘Switch’ Statement and SERVER Superglobal Part 1 (9:44)

Download the folder to follow this demo.

‘Switch’ Statement and SERVER Superglobal Part 2 (12:02)

‘Switch’ Statement and SERVER Superglobal Part 3 (12:23)

The Conditional Operator (12:23)