I’m getting really lazy writing all these beginner PHP tutorials, so this will either be my second last or last one. I’ll be sporadically and scarcely covering some other functions along with this tutorial, but I assure you that I’ll probably post more beginner tutorials when NOVALISTIC 3.0 is up. I’ll only get motivation from there.

OK anyway, the main topics today are if-elseif-else and condition switches.

Every second in your life you need to make a decision. Every millisecond in your script’s life it needs to make a decision too because of the gazillions of possibilities everywhere when it comes to programming, especially PHP.

If you know even JavaScript I’m sure you’ve heard of these:

Example 1: if-else in JavaScript

var n = 6 * 2;

if (n == 12)
{
    alert('n is ' + n);
    return true;
}
else
{
    alert('n is not twelve');
    return false;
}

JavaScript will definitely alert ‘n is 12′ because 6 × 2 is 12 after all.

Anyway, the same goes with PHP, as follows:

Example 2: if-else in PHP

<?php

$n 2;

if ($n == 12)
{
    echo 'n is ' $n;
    return true;
}
else
{
    echo 'n is not twelve';
    return false;
}

?>

Also, notice how similar their syntaxes are. PHP looks kinda like ECMAScript syntax (JavaScript and ActionScript) but it is NOT a type of ECMAScript because PHP belongs on the server, not your web browser or player. You know, this is one of the subtler reasons why I like PHP, lol :D

For the non-programmers:

syntax
Syntax is to programming (and a bit of normal language) as grammar is to English.
ECMAScript
A widely used programming language for web browsers and players, more commonly known as JavaScript or JScript (for Microsoft).

An if-else statement can be built like so:

Example 3: structure of an if-statement

<?php

// The most conventional and commonly-used
// structure with braces.
if (condition)
{
    // Execute these statements if the condition is true
}
else
{
    // Otherwise execute these statements
}

// Alternate syntax, fairly well used and acceptable.
// Most popularly used when templating.
if (condition) :
    // Condition is true
else:
    // Condition is false
endif;

// Don't use this unless it's for very quick echoes,
// it will confuse you and other programmers!
if (condition/* Condition is true */
else /* Condition is false */

/*
Slightly more readable than the above,
but only one line is executed after the condition.
You could try this
*/
if (condition)
    // This line gets parsed after if.
    statement// PHP will only parse before the first semicolon it sees.
    // This line will not be parsed on condition being true.
// If there are any additional commands after the
// first semicolon, this else will throw a parse error.
else
    statement// Likewise here.

?>

Let’s look at a very small example:

Example 3: a basic condition

<?php

// In a PHP form tutorial I will tell you more about $_POST.
$name $_POST['name'];

// The == operator is comparison. You want to find out if $name is Rasmus Lerdorf.
// === means equal AND of same type. Long story.
// != means not equal.
// !== means either not equal or of different types. Longer story.
if ($name == 'Rasmus Lerdorf')
{
    $desc 'The guy who made PHP.';
}
// $name is not Rasmus Lerdorf.
else
{
    /*
    Backslashing (escaping) the single quote tells PHP that the string isn't ended yet;
    that single quote is supposed to be part of the string itself.
    */
    $desc 'I don\'t know this person sorry.';
}

/*
Here I just stuff the variables inside, because
double quotes tell PHP that this string's vars
should be replaced with their values. Much
cleaner than echo $name . ': ' . $desc;
*/
echo "$name: $desc";

?>

What if you want to tell PHP to determine if something evaluates to false instead?

Example 5: negating an if condition

<?php

if (!$condition)
{
    // Condition returned false
}

?>

The else construct is completely optional if you want PHP to do something small only if the condition is true. For example, say you want to keep dividing an even number by two until it becomes odd.

I’ll just tear this snippet out of a simple loop since we’ll focus on loops next time.

Example 6: if without else

<?php

// ...
    
    // % is a modulus operator. I can't believe I forgot to
    // tell you about this... anyway, recalling your division
    // terms, $a % $b gives the remainder of $a divided by $b.
    // The quotient is lost forever.
    if ($n == 0)
    {
        // We still have an even number...
        echo "Still even, I got $n! Halving $n...<br />";
        
        /*
        $a .= $u means $a = $a . $u
        $b += $v means $b = $b + $v
        $c -= $w means $c = $c - $w
        $d *= $x means $d = $d * $x
        $e /= $y means $e = $e / $y
        $f %= $z means $f = $f % $z
        */
        $n /= 2;
    }
    
// ...

?>

What if you want more than one possibility of condition? The elseif clause makes this easy:

Example 7: if-elseif-else example

<?php

// $name is Rasmus Lerdorf
if ($name == 'Rasmus Lerdorf')
{
    echo $name ' made PHP.';
}
// Not Rasmus Lerdorf, but Eric Raymond
else if ($name == 'Eric Raymond')
{
    echo $name ' wrote <cite>The Cathedral and the Bazaar</cite>.';
}
// Neither Rasmus Lerdorf nor Eric Raymond, maybe Matt Mullenweg
else if ($name == 'Matt Mullenweg')
{
    echo $name ' created WordPress!';
}
// None of the above, I don't know who else
else
{
    echo 'I don\'t know who ' $name ' is.';
}

?>

And an example of a not-equals condition:

Example 8: not-equals condition

<?php

if ($username != 'BoltClock')
{
    // exit() terminates the script immediately with an
    // optional error message to spit.
    exit('You are not BoltClock, shoo!');
}

?>

You can also combine various conditions together using || (or) or && (and). When you link two conditions with ||, either one of them has to be true for the whole thing to be true. If both are false the whole thing becomes false. When you link them with &&, both have to be true for the whole thing to be true. I won’t talk about xor because it’s very seldom you’ll have to make use of that, but only ONE of the conditions can be true; if both are true or both are false the whole thing is false.

Example 9: or and and

<?php

// Either... or...
if ($number || $number 10)
{
    // $number doesn't get parsed because of single quotes!
    echo '$number is either greater than 1 and/or less than 10.';
}

// Both... and...
if ($number 200 && $number == 0)
{
    echo '$number is an even number that\'s less than 200.';
}

// You can combine or and and as much as you need to!
// Brackets can help with clarity and ordering...
if (($number $another && $number == 0) || ($number $another && $number == 1))
{
    // Do something here...
}

?>

That’s pretty much about it for if-elseif-else in PHP. There’s another type of construct to replace elseif especially if there’s too many of them, and that is switch. I’ll tell you more about it when I encounter it while working on another tutorial.

Back to top