Prev | Current Page 173 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


CHAPTER 3 ?–  PHP BASICS 99
The if Statement
The if statement is one of the most commonplace constructs of any mainstream
programming language, offering a convenient means for conditional code execution.
The following is the syntax:
if (expression) {
statement
}
As an example, suppose you want a congratulatory message displayed if the user
guesses a predetermined secret number:
$secretNumber = 453;
if ($_POST['guess'] == $secretNumber) {
echo "

Congratulations!

";
}
?>
The hopelessly lazy can forgo the use of brackets when the conditional body
consists of only a single statement. Here??™s a revision of the previous example:
$secretNumber = 453;
if ($_POST['guess'] == $secretNumber) echo "

Congratulations!

";
?>
?– Note Alternative enclosure syntax is available for the if, while, for, foreach, and switch control
structures. This involves replacing the opening bracket with a colon (:) and replacing the closing bracket
with endif;, endwhile;, endfor;, endforeach;, and endswitch;, respectively. There has been
discussion regarding deprecating this syntax in a future release, although it is likely to remain valid for
the foreseeable future.
The else Statement
The problem with the previous example is that output is only offered for the user who
correctly guesses the secret number. All other users are left destitute, completely
snubbed for reasons presumably linked to their lack of psychic power.


Pages:
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185