Page 58 - Open Soource Technologies 304.indd
P. 58
Web Technologies-I
Notes Some programming languages make use of the then keyword (if ... then). PHP does not.
If some conditional expression evaluates to true then PHP performs the associated statement
block. For instance, the following statement will echo out a warning that the value of a variable
is not an integer. It will only generate this message if the expression ! is_int($x) evaluates to true,
which is to say, if it is not a number.
if (!is_int($x)) {
echo ($x . ‘ is not an integer!’);
} If you just want to execute a single statement within an if statement, you do not technically
need the curly brackets, but they are a good habit to get into so you do not forget them.
In the programming concept the Switch statement is sometimes called the
case statement.
Else Statement
The if statement executes a block of code if something is true.
What happens if you want to execute one block of code if something is true and another if it is
false? In this case, PHP has something called the else statement.
The else statement can only follow an if statement and is used to mark off a statement block to
execute if the conditional expression being tested evaluates to false. It does not take its own test
condition expression because it executes in response to the if statement immediately preceding
it returning false.
if (!is_int($x)) {
echo ($x . ‘ is not an integer!’);
}
else {
echo $x . ‘ is a number we can work with!’);
}
Do not forget the curly brackets around both expression blocks. Thinking that the else is part
of the if statement (which technically it is) makes it easy to forget to close the if statement block
before the else statement block.
Elseif Statement
What happens if you want to test for more than simply whether a given expression equates to
true or false, but want to test for and execute code based on a variety of possible conditions? This
is to say, what happens if there are three or more conditions.
PHP has an elseif statement. This allows us to test for another condition if the first one was not
true. The program will test each condition in sequence until:
It finds one that is true. In this case it executes the code for that condition.
It reaches an else statement. In this case it executes the code in the else statement.
It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement
after the conditional structure.
The elseif sturcture looks like this:
52 LOVELY PROFESSIONAL UNIVERSITY