?: operator (the 'Elvis operator') in PHP

The Elvis operator, represented by a question mark followed by a colon (?:), is a ternary operator in PHP that is used to simplify expressions that return a value based on a condition. It is often referred to as the Elvis operator because it looks like a stylized pair of eyes and the top of a head, similar to the hairstyle of Elvis Presley.

The basic syntax of the Elvis operator is:


$age = 25;

// Using the ternary operator to determine if a person is an adult or a child
$status = $age >= 18 ? "adult" : "child";

echo "The person is a $status";

If the condition is true, then value1 is returned; otherwise, value2 is returned.

For example:


$age = 20;
$can_drink = $age >= 21 ? true : false;

if ($can_drink) {
  echo "You can legally drink alcohol.";
} else {
  echo "You cannot legally drink alcohol.";

In this example, the value of $can_drink will be false because $age is not greater than or equal to 21.

The Elvis operator can be used to simplify expressions that would otherwise require an if-else statement. It is particularly useful when working with functions that return a value that might be null or false, as it allows you to specify a default value to be used if the function returns null or false.

For example:


function get_user_name()
  // Some code that retrieves the user's name from a database or other source
  return 'John Doe';

$name = get_user_name() ?: 'Guest';

echo "Welcome, $name!";

In this example, if the get_user_name() function returns a non-empty string, it will be assigned to the $name variable. If the function returns an empty string or null, the string 'Guest' will be assigned to the $name variable instead.