Welcome to part 3 of these basics of PHP tutorials. In this part, we are going to learn how to make if statements.

The syntax for an if statement look like this:

if (condition) {
     //Run this code if condition is true
}

Where it says "condition" we insert a Boolean expression, an expression that either has a value of true or false. If the condition is true, the code inside the brackets will be executed. Here's an example:

if (3 > 2) {
     //This code would run because 3 is greater than 2
}

The Boolean expression 3>2 would return true, because 3 is greater than 2. Since it is true, the code inside the brackets would be executed. After the code in the brackets is executed, it would continue executing any code after the closing bracket.

Now consider this:

if (2 > 3) {
     //This code would not run because 2 is not greater than 3
}

The Boolean expression 2>3 would return false, because 2 is not greater than 3. Since it is false, the code inside the brackets would be skipped and any code after the ending bracket would continue on being executed.

Of course there are many other comparison operators besides > that you can use as well.

  • > returns true if the value to the left is greater than the value to the right.
  • >= returns true if the value to the left is greater than or equal to the value to the right
  • < returns true if the value to the left is less than the value to the right.
  • <= returns true if the value to the left if less than or equal to the value to the right.
  • == returns true if the value to the left is equal to the value to the right.
  • != returns true if the value to the left is not equal to the value to the right.

We can use variables for comparison as well.

if ($value == $value2) {
     print "$value equals $value2";
}

You can add another block of code called "else" that executes if the condition is not true.

if ($value == $value2) {
     print "$value equals $value2";
} else {
     print "$value does not equal $value2";
}

You can even add more blocks of code that execute if the initial condition statement is false, but another condition is true:

if ($value == $value2) {
     print "$value equals $value2";
} elseif ($value < $value2) {
     print "$value is less than $value2";
} else {
     print "$value is greater than $value2";
}

You can also combine multiple conditional statements into one.

if ($value == $value2 && $value2 == $value3) {
     print "$value, $value2, and $value3 are all equal"
} elseif ($value == $value2 || $value2 == $value3) {
     print "$value is equal to $value2 and/or $value2 is equal to $value3"
}

A statement consisting of two statements joined by && will only return true if both statements are true.
A statement consisting of two statements joined by || will return true if either of one of the two statement is true, or if both are true.

Be Sociable, Share!