PHP Shortcuts - the ternary operator
The ternary operator in PHP is basically a shorthand way of writing conditional statements, for which we would usually use the familiar if
and else
etc.
For example, in a program that decides what I'm going to do in my lunch hour:
if($is_friday) { $activity = 'go to the pub'; } else { $activity = 'stay at work'; }We could write this with less code (less code is better, right?)
$activity = $is_friday ? 'go to the pub' : 'stay at work';So, what happens here is if
$is_friday
equates to TRUE
, the value after the question mark ('go to the pub') is assigned to the variable $activity
. If $is_friday
equates to FALSE
then the value after the semi-colon ('stay at work') is assigned to $activity
instead.
The other neat thing about the ternary operator is we can use it as part of an echo
statement to decide what we're doing and output it to the page in one easy line of code like so:
It's my lunch hour and today I'm going to <?php echo $is_friday ? 'go to the pub' : 'stay at work'; ?>
.
Hooray for ternary operators, unfortunately it's Thursday today so I'll be staying at work!
Please refresh the page and try again.