PHP: Other Conditionals
Derek Bridge
Department of Computer Science,
University College Cork
PHP: Other Conditionals
Aims:
- to practice writing programs with conditionals
- to learn about the ternary conditional operator
- to learn of the switch statement
Class exercise
- Compare different solutions to the exercise set at the
end of the previous lecture
The conditional operator
- In the previous exercise, one of two values (either
'Ms.' or 'Mr.') is required, depending on a Boolean
expression (
$sex == 'F'
)
- PHP provides a conditional operator that can
achieve the same effect without using an
if-else
statement
- Example of an expression using this operator:
$sex == 'F' ? 'Ms.' : 'Mr.'
- Example of using this in an assignment to achieve the same
as in the previous exercise:
$title = $sex == 'F' ? 'Ms.' : 'Mr.';
The conditional operator
- In general
Boolean-expression ? value1 : value2
The expression evaluates to value1 if the Boolean expression
is true, otherwise it evaluates to value2
- Class exercise:
- Write an assignment statement that uses the conditional operator
to store 'AM' in
$period
if $hour
is less than 12, and 'PM' otherwise
- Rewrite the following
echo
statement so that
it outputs 'eurine' instead of 'eurines' when $debt
contains 1:
echo "You owe {$debt} eurines";
The conditional operator
- Don't overuse it: it can be quite cryptic
- Advanced observation (arity)
- Some operators are unary, e.g.
(int)
- Some are binary, e.g.
+,-,*,/,%,<,>
- This one is ternary
- Advanced observation (precedence and associativity)
- It has quite low precedence, so it often needs
parentheses (advice: wrap it in parentheses anyway)
- It is left-associative
The switch
statement
- (Not covered/not examined in CS1109. Interested students
should consult a textbook or the
entry in the on-line PHP manual)
- Often the value of a single variable or expression
determines what statements to execute
- In such cases,
switch
can be used in place of
if-else
s
The switch
statement
if ( $x == 0 )
{
do something
}
elseif ( $x == 1 )
{
do something
}
elseif ( $x == 2 )
{
do something
}
else
{
do something
}
|
switch ( $x )
{
case 0:
{
do something;
break;
}
case 1:
{
do something;
break;
}
case 2:
{
do something;
break;
}
default:
{
do something;
break;
}
}
|