PHP Knowledge Base
The Ternary Operator
Example of Standard if/then/else
Conditional Statement
if( $valid ) { $x = 'yes'; } else { $x = 'no'; }
Above Example Written Using the Ternary Operator
$x = $valid ? 'yes' : 'no';
Verifying the (non-)existence of the value and using the default 2
NOTE:
??
is the equivalent of isset()
.Example #1
echo $mainCategory ?? 'The category does not exist';
Example #2
echo "<td>$sell_date</td>" ?? "<td> </td>";
Example #3
Replace
if(isset($_SESSION['username'])) { echo $_SESSION['username']; }
With
echo $_SESSION['username'] ?? '';
Ternary Shorthand (PHP 5.3+)
Example of Standard if/then
Conditional Statement
if( !$start ) { $start = 1; }
Above Example Written Using Ternary Shorthand
$start = $start ?: 1;
NULL