The Ternary Operator in PHP
In this video we will talk about the ternary operator in PHP: its syntax, what it is good for and how to use it to implement some nice features.
Patkos Csaba
•
1 min read
From The Video
The ternary operator allows us to simplify some PHP conditional statements. We'll see how it can be used, with test-driven development and refactoring, to simplify code like:
1 |
<?php
|
2 |
|
3 |
$result = null; |
4 |
|
5 |
if (5>3) { |
6 |
$result = "Bigger"; |
7 |
} else { |
8 |
$result = "Less"; |
9 |
}
|
Written using a ternary operator, we can write the above comparison as:
1 |
<?php
|
2 |
$result = 5 > 3 ? "Bigger" : "Less"; |
This is obviously a much simpler way to write relatively easy to understand conditional statements and something we should consider when writing future code,



