PHP If Then

The PHP if/then statement is very easy to understand when using basic logic. If you think about it, every time there is an “if”, there will always be a “then”.

If I save my money, then I can buy a new car.
If you are caught driving drunk, then you will go to jail.

The same principle applies to the if/then statement in PHP.

Simple If/Then Statement

Let’s start off with a simple example of a basic PHP if statement:


$color = "black";

if ( $color == "black" ) {
echo "I have 5 gallons of black paint.";
}

This bit of code would display:

I have 5 gallons of black paint.

Notice that the string value of “$color” is “black”. The if statement says that if $color equals (==) black, then echo “I have 5 gallons of black paint.”

Here we used the “==” operator.

Notice how a small modification can change the results entirely:


$color = "black";

if ( $color != "black" ) {
echo "I have 5 gallons of black paint.";
}

This bit of code would display nothing at all. Why?

Because we changed the if statement to “not equals” (!=) instead of equals (==) by using the “!=” operator.

A complete list of PHP operators are shown on the PHP Operators page.