O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Making Decisions

With the if( ) construct, you can have statements in your program that are only run if certain conditions are true. This lets your program take different actions depending on the circumstances. For example, you can check that a user has entered valid information in a web form before letting her see sensitive data.

The if( ) construct runs a block of code if its test expression is true. This is demonstrated in Example 3-1.

Example 3-1. Making a decision with if( )

if ($logged_in) {
   print "Welcome aboard, trusted user.";
}

The if( ) construct finds the truth value of the expression inside its parentheses (the test expression). If the expression evaluates to true, then the statements inside the curly braces after the if( ) are run. If the expression isn't true, then the program continues with the statements after the curly braces. In this case, the test expression is just the variable $logged_in. If $logged_in is true (or has a value such as 5, -12.6, or Grass Carp, that evaluates to true), then Welcome aboard, trusted user. is printed.

You can have as many statements as you want in the code block inside the curly braces. However, you need to terminate each of them with a semicolon. This is the same rule that applies to code outside an if( ) statement. You don't, however, need a semicolon after the closing curly brace that encloses the code block. You also don't put a semicolon after the opening curly brace. Example 3-2 shows an if( ) clause that runs multiple statements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required