Lesson 7

Making Decisions

One of the most useful aspects of a programming language is the ability to do different actions in different situations. If it rains today I use an umbrella, but if it is sunny I wear my sunglasses. When the light is red I stop; when it is green I go; and when it is yellow I go fast.

In this lesson you learn how to use various conditional statements to make the program perform differently depending on the situation.

If/Else

The most recognizable conditional statement is the if statement. You use the if statement to tell the program to execute some code if a given condition is true. Optionally, you can add an else statement to tell the program what to do if the condition is not true.

Basic If Statements

The most basic if statement consists of the condition that is being evaluated along with the code to be executed enclosed in curly braces This is how you write a basic if statement:

if (some condition) {
    some lines of PHP code here;
    that are performed;
    if the condition evaluated to true;
}
warning

If you have only a single line of code, you can leave off the curly braces. However, this can cause errors if you later add another line and do not add the curly braces.

Following is an example of how you could report on a rainy day. The results look similar to Figure 7-1.

 <html> <head> <title>Lesson 7a</title> </head> <body> <h1>Weather Report</h1> <?php $weather ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.