Elvis Operator
Last updated onThe PHP Elvis Operator is a shorthand operator that simplifies certain conditional assignments, which is a colloquial term for a specific use case.
Let’s delve into the Elvis operator syntax.
PHP Elvis Operator Syntax
The Elvis Operator simplifies assignments, where the goal is to set a variable to a default value if the condition is false. Dubbed the “Elvis Operator” it earns its name from the emoticon-like resemblance of the ?: part to Elvis Presley’s face.
Here’s an example:
<?php
// Traditional ternary operator
$username = isset($_GET['user']) ? $_GET['user'] : 'Guest';
// Elvis Operator equivalent
$username = $_GET['user'] ?: 'Guest';
?>
In the example above, if $_GET['user']
is set, $username
will be assigned its value; otherwise, it will be assigned the default value ‘Guest’. The Elvis Operator provides a concise and readable way to achieve this.
Keep in mind that the Elvis Operator might not be as well-known as the standard ternary operator, so using it should be done with consideration for code readability and the familiarity of your development team with this shorthand notation.
Let’s see more examples.
PHP Elvis Operator Examples
Here are a few more examples of using the Elvis Operator in PHP:
Using with function return values:
<?php
// Traditional ternary operator
$result = performOperation() !== null ? performOperation() : 'Default';
// Elvis Operator equivalent
$result = performOperation() ?: 'Default';
?>
In this example, the Elvis Operator ?:
condenses the ternary operation into a more compact form. It checks if the result of performOperation()
is truthy (not null
or equivalent), and if so, assigns that value to $result
. If the result is false, it assigns the fallback value 'Default'
.
Let’s see another example of how to set a default value for an array element using the Elvis Operator.
Providing a default value for an array element:
<?php
// Traditional ternary operator
$color = isset($theme['color']) ? $theme['color'] : 'Blue';
// Elvis Operator equivalent
$color = $theme['color'] ?: 'Blue';
?>
Here, the Elvis Operator ?:
condenses the conditional assignment. It checks if $theme['color']
is truthy (i.e., not null or equivalent) and, if true, assigns that value to $color
. If $theme['color']
is false, it assigns the default value 'Blue'
. This streamlined syntax offers a more concise and readable way to handle the same conditional assignment, making the code more elegant and easier to understand.
Let’s summarize it.
Wrapping Up
the PHP Elvis Operator provides a succinct and expressive shorthand for certain conditional assignments, streamlining code and enhancing readability. Its syntax, reminiscent of Elvis Presley’s face with the ?:
combination, simplifies the process of setting a variable to a default value when a condition is false. While not as widely known as the standard ternary operator, the Elvis Operator proves to be a valuable tool in scenarios where brevity and clarity are essential.