1.2.1122. Should Use Ternary Operator¶
Ternary operators are the best when assigning values to a variable.
They are less verbose, compatible with assignation and easier to read.
<?php
// verbose if then structure
if ($a == 3) {
$b = 2;
} else {
$b = 3;
}
// compact ternary call
$b = ($a == 3) ? 2 : 3;
// verbose if then structure
// Works with short assignations and simple expressions
if ($a != 3) {
$b += 2 - $a * 4;
} else {
$b += 3;
}
// compact ternary call
$b += ($a != 3) ? 2 - $a * 4 : 3;
?>
See also Ternary Operator and Shorthand comparisons in PHP.
1.2.1122.1. Connex PHP features¶
1.2.1122.1.1. Suggestions¶
Use the ternary operator
1.2.1122.1.2. Specs¶
Short name |
Structures/ShouldMakeTernary |
Rulesets |
|
Exakat since |
0.8.5 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Instant (5 mins) |
Precision |
Very high |
Examples |
|
Available in |