Page 64 - Open Soource Technologies 304.indd
P. 64
Web Technologies-I
Notes $hours = ($hours < 13)? $hours: $hours –= 12;
Since the ternary operator is, in fact, an operator, it returns a value, which is the value of one of
the expressions. If the condition evaluates to true, then the first value is returned (value_if_true),
otherwise the second value is returned (value_if_false). This means that the expressions for the
true and false values need to be things that evaluate to values, not full blown statements, just
simple expressions.
The alternative syntax makes use of labels for all components of the if statement. The curly brackets
are omitted. Since there are no curly brackets, there needs to be some way to specify the end of
the statement block. For this we use and endif label.
The code looks like this:
if (condition):
statements;
elseif (condition):
statements;
else:
statements;
endif;
if ($x < 0):
echo “Cannot use a negative number.”;
elseif ($x > 999999):
echo “Cannot use that big a number.”;
else:
doSomethingWith($x);
endif;
Alternate Switch
The alternate switch statement has the same syntax as the alternate if statement. The curly brackets
are omitted and a closing end switch is used to denote the end of the statement block.
switch ($someNumber):
case 0:
echo “Zero is not a valid value.”;
break;
case $someNumber < 0:
echo “we cannot use negative numbers.”;
break;
default:
echo “Ready to compute.”;
break;
endswitch;
58 LOVELY PROFESSIONAL UNIVERSITY