- Instant help with your Php coding problems

Use PHP ternary operator

Question:
How to use PHP ternary operator?
Answer:
$city = isset($req->city) ? $req->city : 'NA';
Description:

There are cases when we need to use simple conditional structures in our PHP code. In most cases, we use a simple if else structure like this:

$name = '';

if (isset($_GET['name'])) {
    $name = $_GET['name'];
} else {
    $name = 'Guest';
}

However, in such a simple case, the above code is unnecessarily long and makes it less readable. The ternary operator was created to solve this problem. From the above code, we can write the following single-line if-else structure:

$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';

The exact syntax is:

(expr1) ? (expr2) : (expr3)

The ternary operator can also be nested, but in this case, readability is compromised:

$colorCode = '0000FF';

$color = ($colorCode == 'FF0000') ? 'red' : (($colorCode == '00FF00') ? 'green' : (($colorCode == '0000FF') ? 'blue' : 'Unknown'));

A more common case, however, is when the basic syntax is further simplified. If the expression is not satisfied, use the specified value, otherwise use the original expression. This is called the Null Coalescing operator. For example, use the name parameter from the URL if exists or use the string Guest if not:

$name = $_GET['name'] ?? 'Guest';

 

Share "How to use PHP ternary operator?"
Tags:
ternary operator, one line if, php, conditional operator
Technical term:
Use PHP ternary operator
Interesting things
ChatGPT in a nutshell