Hudzilla.org - the homepage of Paul Hudson
Contents > Introducing PHP > How PHP is written Wish List | Report Bug | About Me ]

2.6.8     Conditional statements

This is NOT the latest copy of this book; click here for the latest version.

PHP allows you to choose what action to take based upon the result of a condition. This condition can be anything you choose, and you can combine conditions together to make for actions that are more complicated. Here is a working example:

<?php
    $Age
= 20;
    if (
$Age < 18) {
        print
"You're young - enjoy it!\n";
    } else {
        print
"You're not under 18\n";
    }

    if (
$Age >= 18 && $Age < 50) {
        print
"You're in the prime of your life\n";
    } else {
        print
"You're not in the prime of your life\n";
    }

    if (
$Age >= 50) {
        print
"You can retire soon - hurrah!\n";
    } else {
        print
"You cannot retire soon :( ";
    }
?>

PHP evaluates if statements left to right, meaning that it first checks whether $Age is greater or equal to 18, then checks whether $Age is less than 50. The double ampersand, &&, means that both statements must be true if the print "You're in the prime of your life\n" code is to be executed - if either one of the statements is not true for some reason, "You're not in the prime of your life" is printed out instead.

As well as &&, there is also || (the pipe symbol printed twice) which means "OR". In this situation, if any of the conditions being checked in an if statement is true, the whole statement is considered true.

You have a vast array of ways to check statements, of which we have just looked at < (less than) and <= (less than or equal to), and >= (greater than or equal to). We will be looking at the complete list later, but first I want to mention one key check: ==, or two equals signs put together. That means, "is equal to". Therefore 1 == 1 is true, and 1 == 2 is false.

Did you notice that if statements use the code blocks I mentioned earlier? The code to be executed if the statement is true is in its own block (remember a block starts with { and finishes with }), and the code to be executed otherwise is in an else block. This stops PHP from trying to execute both the true and false actions.

One key thing to note is that PHP practises "if statement short-circuiting" - this is where PHP will try to do as little conditional work as possible, so it basically stops checking conditional statements as long as it is sure it can stop. For example:

if ($Age > 10 && $Age < 20)

If $Age evaluates to 8, the first check ($Age > 10) will fail, so PHP will not even bother checking it against twenty. This means you can, for example, check whether a variable is set and whether it is set to a certain value - if the variable is not set, PHP will short-circuit the if statement and not check its value, which is good because if you check the value of an unset variable, PHP will flag an error!

A helpful addition to if statements is the elseif statement, which allows you to chain commands together in a slightly more intelligent way. Here is an example script:

<?php
    
if ($Age < 10) {
        print
"You're under 10";
    } elseif (
$Age < 20) {
        print
"You're under 20";
    } elseif (
$Age < 30) {
        print
"You're under 30";
    } elseif (
$Age < 40) {
        print
"You're under 40";
    } else {
        print
"You're over 40";
    }
?>

You could reach the same effect by having lots of if statements, however this is a slightly neater way of doing things. The downside of this system is that the $Age variable needs to be checked repeatedly.

If you only have one line of code to execute, you can do without the braces entirely. Given that there is only the tiniest fraction of a speed difference between using braces and not using braces, it's usually down to a readability issue.

So, these two code chunks are the same:

if ($foo) {
    echo
$bar;
}

if (
$foo) echo $bar;




<< 2.6.7 Comments   2.6.9 Case switching >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
vinod - 05 Dec 2008

Do you have any example for array

vinod - 05 Dec 2008

Do you have any example for array

Deepshikha tanwar - 05 Dec 2008

Can array pass through REQUEST variable

leglez - 05 Dec 2008

He said that \n newline switch doesnt work in the browser earlier he said thats for command lines and that </br> is for browsers

tiwiex@yahoo.com - 05 Dec 2008

this actually should have been mad earlier. i noticed that the \n newline switch does not work on my browser. <br> works anyway.

Jasen Betts - 05 Dec 2008

Does shortcut boolean evaluation work outside of if statements?

in C I can say

age < 10 && printf ("you're less younger than 10") ;

and it works as expected...

some would call this obfuscation :)

bye.

PS: how-come all the comments have the same date (todays)
is this site new today (20 July)

TxtEdMacs - 05 Dec 2008

I have already written some rather extensive php code that seemed to require using the nested structure using the:

if () {
// gather ones that fit this pgrep_match() set
} elseif () {
// gather the next set ...
} elseif () {
...
} elseif () {
// nth set
} else {
// be done with it!!
}

This was really large since I was trying to match strings that were associated with various robots, spiders, etc. that are found on web logs. We wished to remove those to keep the count and statistics on visitors more aligned with reality. I had assumed that once the match was found on the passed string all others were ignored. The code seemed to work properly, however, if I am indeed wrong would it require a "break;" command (as used in the switch/case tests) to ignore the rest of the code?

pracphp@spam.trace.yp.cx - 05 Dec 2008

Caveat for Perl coders - PHP has found the lost 'e' in elseif:

Perl: } elsif {
PHP : } elseif {

A PHP User - 05 Dec 2008

It is vey important to note that since version 3, PHP uses short boolean evaluation.

In short boolean evaluation, the remainder of the expression is not evaluated when it can have no influence on the outcome of the evaluation.

This means that, when execution the following code, you will never see the text "Hello, world!", however you will see "This is bar.".

<?php
function foo()
{
printf ("Hello, world!\n");
return TRUE;
}

function bar()
{
printf ("This is bar.\n" );
return TRUE;
}

if ( TRUE || foo() ) {}

if ( FALSE && foo() ) {}

if ( TRUE && bar() ) { }
?>

Luud Heck

Maung - 05 Dec 2008

One of the great things in this book is the author shows you some of the concept behind PHP. If you know how PHP works, you can become more creative. For example, the following is the excerpt from "conditional statements".

....................
One key thing to note is that PHP practises "if statement short-circuiting" - this is where PHP will try to do as little conditional work as possible, so it basically stops checking conditional statements as long as it is sure it can stop.
....................

Now, I'll show how this can be applied.
//......
$link_id = mysql_connect($dbhost, $dbname, $dbpass);
if (!$link_id) {
die("Connection failed to the host $dbhost");
}
//......
I can rewrite the above code as
//......
$link_id = mysql_connect($dbhost, $dbname, $dbpass) or
die("Connection failed to the host $dbhost");
//......
As long as return value of the mysql_connect is true, it will not bother to read die() statement. It is rare to find this kind of book which can cover some of the PHP concepts. I had confused over differences between Double quotes and single quotes before reading your book. Now I think I understand. Your book is helping me alot. Thank you Paul. Thank you so much. Your book is really great for me.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is zero plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow