Changes

Jump to: navigation, search

PHP Flow Control and Looping

21 bytes added, 17:15, 31 May 2007
PHP Conditional Statements
== PHP Conditional Statements ==
Just about everything in life revolves around decisions. We wouldn't get very far through the day if we weren't able to decide what to wear, what to eat and which way to drive to work. Similarly computers would be of little use without some innate ability to evaluate choices and make decisions. If all we were able to do was provide as a computer with a set of instructions that simply followed one after the other with no ability to make choices based on specific criteria, none of the software we have today would exist.
Conditional statements provide the core of building decision making into scripting langauges languages such as PHP. Conditional statements essentially control whether a part of a script is executed depending the result of a particular expression (i.e whether an expression returns a boolean ''true'' or ''false'' value). The two types of conditional structures provided by PHP (and most other programming langauges) are ''if'' and ''if ... else''. In this section we will take a close look at each of these condtional structures, and also provide some examples of their use.
=== The PHP ''if'' Statement ===
<pre>
<?php
$myVar = 10;
if (i < 2)
</pre>
In the above example if i $myVar is less than 2 then the expression will be evaluated as being ''true'', otherwise it will be returned as ''false''
The next step in constructing an if statement is to specify what action should be taken if the expression is evaluted to be ''true''. This is acheived achieved by placing the lines of script to be executed in open and closing braces after the if statement:
<pre>
if (i < 2)
{
document.writeln (" echo 'The value of i myVar is less than 2")'; i$myVar++;
}
</pre>
Note that if there is only one line of script to be performed if the ''if'' expression is ''true '' then the braces are optional:
<pre>
if (i < 2)
document.writeln ("echo 'The value of i myVar is less than 2")';
</pre>
Whilst this is perfectly valid JavaScript PHP it is recommended, for the purposes of consistent scripting style, that the braces be used even for a single line of script after the 'if' statement.
=== The JavaScript PHP ''if ... else'' Statements ===
The ''if'' statement above allows you to specify what should happen if a particular expression evaluates to ''true''. It does not, however, provide the option to specify something else that should happen in the event that the expression evaluates to be ''false''. This is where the ''if ... else'' construct comes into play.

Navigation menu