W3docs

?: 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.

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 ternary operator is:

The basic syntax of the ternary operator in PHP

<?php

$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:

Example of the ternary operator in PHP

<?php

$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 standard ternary operator uses ? :, while the Elvis operator uses ?: (without the middle colon). The key difference is that the Elvis operator omits the middle value and evaluates the left-hand expression twice if it is truthy. Because of this, 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:

Example of Elvis operator instead of if-else statements in PHP

<?php

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. Unlike the standard ternary operator, which requires a value for both the true and false branches, the Elvis operator only requires a fallback value, making it more concise for default assignments.