With its extensive features and functionalities, PHP is a strong programming language that aids developers in building reliable applications. The ternary operator and the coalescing operator are two of PHP's most beneficial operators. These operators let programmers (like you) create clear, effective code that can deal with default values and conditional logic. Since PHP 8, the language's capabilities were expanded by adding a new operator known as the null safe operator. We will learn how to use the null safe operator, ternary operator, and coalescing operator in PHP to increase the productivity and readability of your code.
Ternary operator in PHP
Since way back in PHP 4 (early 2000s), the ternary operator has been available to programmers to use within their code. A popular operator that is used in a lot of codebases, especially open-sourced software, the ternary operator is a great and quick way to create logic without the need for bloated if-else statements. The idea behind ternary operators is to allow developers to create the same logic as if-else statements but in a one-liner. In code, we program line-by-line, that's what's read by PHP's parser to turn our code into working functionality, therefore each line is treated differently. If you have loads of if statements, (especially those that are really simple), having an if-else statement will (if indented correctly) take up at least five lines of code. Now, using a ternary operator, that could be just one. Not only does that create cleaner code, but code that can be written faster! Let's explore a common if-else statement and compare that to the powerful, yet simple-to-use ternary operator in PHP.
The first simple if-else alternative example of a ternary operator in PHP is the "?:" (question mark, colon) operator. Here you will see our ternary operator and our equivalent if-else statement. They both do the same thing but using ternary, makes for easier-to-read code.
$test = 1;
# Outputs: Yes
echo $test === 1 ? 'Yes' : 'No';
# Is the same as
if ($test) {
echo 'Yes';
} else {
echo 'No';
}
Coalescing operator in PHP
Next up which has been available since PHP 7 in 2015, and the coalescing operator was added. This operator takes the well-established ternary operator style, which is a one-liner and allows you to check for null values by returning the first non-null value in your expression. This replaces the need for an if-else statement like the ternary operator but takes it one step further by checking for null values. Sometimes in PHP, our variables become (or even start out) null. If null values, there's not a lot they can do. They can't print something to screen for your user, and they can't trigger a function that requires a non-null value. Instead of having to manually check if a variable is a null value, we can instead use the coalescing operator and be part of a one-liner!
The term coalescing is when you combine multiple elements together into a single thing. Within PHP, that's combining a series of expressions into one single expression (one-liner). By using this operator your code quickly becomes more concise and easier to read code. The example below shows that if '$foo' wasn't null, that would be echoed, otherwise we'd get 'bar'. In this example, we get 'bar', because the '$foo' variable is null.
# Outputs: bar
$foo = null;
echo $foo ?? 'bar';
# Is the same as
if (is_null($foo)) {
echo 'bar';
} else {
echo $foo;
}
# Or written in a different way
if ($foo !== null) {
echo 'bar';
} else {
echo $foo;
}
Null safe operator in PHP
Finally, since PHP 8 in 2020, the null safe operator was added. Combining both ternary and coalescing operators together to make the null safe operator. The buzz in the PHP community around null safe operators rocketed as it solved common and annoying problems programmers alike faced. The null safe operator is achieved by using '?->' similar to '->' on a PHP object but with a question mark in front. In object-oriented programming, you use classes, objects, and properties to create functionality. It's common when calling a class' functions that you may need to chain other functions together to obtain a particular result. You may for example get a property and then be required to get a nested property from the same class. That may look like the following simple example. Here we're getting the property of the object rather than calling a method on it. Prior to PHP 8, if 'prop' was null that would trigger an error because you cannot get 'method' on a null object. This is where null safe operators come in to save the day.
$obj?->prop?->method();
Null-safe operators are a great way to chain nested properties together without the risk of triggering a fatal PHP error if one (or more) are null. Before PHP 8, this could be achieved in a somewhat longer form using coalescing operators. In this simple OOP example, we have a class 'Phone' in which we're trying to get the phone's version. Because we've forced null on the variable (our pretend class) we would get a fatal PHP error if called without the null safe operator. However, with null safe operators, we don't get an error, we fact we get no output.
# This is null safe
$phone = null;
echo $phone?->getVersion();
# This is not null safe and triggers a fatal error
$phone = null;
echo $phone->getVersion();
Conclusion
In conclusion, the ternary operator in PHP is a great way to create short and to-the-point conditional statements. It can make code more legible and maintainable, as well as cut down on the amount of code required to carry out basic conditional checks. It can be especially helpful in scenarios where a straightforward if/else statement is required to do an immediate check and set a variable value appropriately.
Coalescing operators are a helpful PHP feature that can help code become simpler and supply default values for variables that might not exist. They enable programmers to create shorter lines of code and do away with the need for numerous if/else statements to verify the existence of variables. Developers can build more understandable, maintainable code that has fewer defects and is simpler to maintain by employing coalescing operators, since PHP version 7.
PHP's null safe operators are a helpful feature that may streamline code and guard against fatal mistakes. They give programmers safe access to null object attributes and methods without the need for clumsy if/else statements. Null-safe operators enable programmers to create shorter, more understandable lines of code that are easier to maintain and less prone to problems. Remember that this functionality was added in PHP 8.0, therefore older versions of the language will not have it available.
- Use ternary operators for keeping simple if-else statements to a minimum
- Combine that with coalescing operators to safeguard against null values
- Finally, use null safe operators when working with OOP-style codebases.