Learn
Booleans and Comparison Operators
Ternary Operator

PHP offers a short-hand syntax to conditionally return a value. Before learning it, let’s consider some example code:

$isClicked = FALSE; if ( $isClicked ) { $link_color = "purple"; } else { $link_color = "blue"; }

In the code above, our condition checks the value of the $isClicked variable. If it’s TRUE we assign $link_color to "purple", otherwise we assign it the value "blue". Our code is somewhat repetitive—the code in each code block is only slightly different.

A ternary operator (?:) is another conditional operator. It takes three operands and returns a value:

  • The first operand is a condition to check. This is followed by a question mark ?.
  • The second operand is an expression to return if the condition is TRUE. This is followed by a colon (:).
  • The third operand is an expression to return if the condition is FALSE.

Let’s see our previous example refactored with the ternary operator:

$isClicked = FALSE; $link_color = $isClicked ? "purple" : "blue";

The ternary operator allows us to write fewer lines of code while maintaining readability.

Note that code in the expression will be executed, but the intended use of the ternary is to conditionally return a value not to execute code.

Let’s get some practice with the ternary operator!

Instructions

1.

In a previous exercise, you wrote a function chooseCheckoutLane() using an if/else. Write a version of this function called ternaryCheckout() which accomplishes the same functionality using a ternary operator instead of an if/else.

This function should take in a single number argument representing the number of items a customer has. If the customer has 12 items or fewer, the function should return "express lane". Otherwise, the function should return "regular lane".

2.

In a previous exercise, you wrote a function canIVote() using an if/else. Write a version of this function called ternaryVote() which accomplishes the same functionality using a ternary operator instead of an if/else.

Your function should take in a number representing an age, and return the string “yes” if the age is greater than or equal to 18, and the string “no” it’s not.

3.

Test each of your functions twice—once with an input will fulfill the condition and once with an input that won’t. Make sure to print the results to the terminal.

Folder Icon

Take this course for free

Already have an account?