Home /PHP/IF Statements

If Statements

In PHP, if statements are the foundation of programming logic. If statements contain statements that are only executed when the condition is satisfied. Let’s go through an example.

Simple If Statement

Example

$myVar = 1;
if($myVar==1)
{
    echo "It worked.";
}

Result

It worked.

The if statement simply says, if the variable $myVar is equal to 1, then execute the statements inside of the brackets. If our variable had been equal to two, the statements inside of the if would not have been executed.

Comparison Operators

You already used one of these above. It was the ==, which asks if the thing before it is equal to the thing after it. If the answer is yes (true), we execute the statement. However, if the answer would have been no (false), we would not have executed the statement.

Example

$x = 7;
if($x===7)
{
    //this would be executed
}
if($x==="7")
{
    //not executed because === checks type
}
if($x!=8)
{
    //this would be executed
}
if($x>8)
{
    //not executed
}
if($x<8)
{
    //this would be executed
}
if($x>=7)
{
    //this would be executed
}
if($x<=6)
{
    //not executed
}

You can see what each one of the comparison operators does above, but what if you wanted to use two of them simultaneously? You can do this using logical operators.

Example

$x = 7;
if($x>=6 && $x<=8)
{
    //executed because 7 is between 6 and 8
}
if($x==7 || $x>=8)
{
    //executed because $x is equal to 7
}
if(!($x==6))
{
    //executed because $x is not 6
}

If, Else If, and Else

If statements can be simple, but they can also be more useful when combined with else if and else.

Example

$x = 6;
if($x == 8)
{
    $x++;
    echo "if($x = 8) and now x = " . $x;
}
else if ($x == 7)
{
    $x = 4;
    echo "else if ($x = 7) and now x = " . $x;
}
else
{
    $x = 20;
    echo "else and now x = " . $x;
}

Result

else and now x = 20

You might ask yourself, “What is the point in an else if statement?” Consider this example:

Example

$x = 8;
if($x == 8)
{
    $x++;
    echo "if($x = 8) and now x = " . $x;
}
if ($x == 7)
{
    $x = 4;
    echo "else if ($x = 7) and now x = " . $x;
}
else
{
    $x = 20;
    echo "else and now x = " . $x;
}

Result

if(9 = 8) and now x = 9 else and now x = 20

Why did the if($x == 8) and the else both execute their statements? Think of if statements as completely separate conditionals, but else if and else build off of the preceding if. If you had two if statements, they would execute independently, as shown above.