簡介
三元運算子,在許多程式語言都會有,基本上您可以把它想成是if的一種簡化.
直接來看例子比較:
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
可以直接參考官方文件:PHP Comparison Operators - Ternary Operator
更簡短寫法
PHP Shorthand Overview - Assignment Operators (Ternary Operator)
來個範例:
// Equal to $foo = $bar ? $bar : $baz;
$foo = $bar ?: $baz;