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— editable, runs on the server

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

For example:

Example of the ternary operator in PHP

php— editable, runs on the server

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— editable, runs on the server

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.