Developer
PHP
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP VariablesPHP ConstantsPHP OutputPHP Data TypesPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

PHP Shorthand Conditionals

PHP has two special shorthand conditional operators.

PHP Ternary Operator

The ternary operator is a short way to perform a if statement.

Ternary Syntax

(condition) ? (on true) : (on false)
  • If the condition is true, the result of on true expression is returned.
  • If the condition is false, the result of on false expression is returned.
  • Since PHP 5.3, you can omit the on true expression. (condition) ?: (on false) returns the result of condition if the condition is true, otherwise the result of on false expression is returned.

PHP Ternary Operator Example


<?php
$username = 'Hyvor';
echo 'Hello' . ($username ?: 'Guest'); // hello hyvor, because $username returns true

echo '<br>';

$username = null;
echo 'Hello' . ($username ?: 'Guest'); // hello guest, because $username returns false

echo '<br>';

// another example
$var = 5;
$isGreaterThan2 = $var > 2 ? true : false;
var_dump($isGreaterThan2);

Run Example ››
It is not recommend to use nested ternary expressions. PHP's behavior when using more than one ternary operator within a single statement is non-obvious. So, use ternary operator only for simple conditions.

PHP Null Coalescing Operator

PHP's null coalescing operator is a useful new feature which was introduced in PHP 7.

Null coalescing operator can be used to assign default values to a variable.

In the example below, the null coalescing expression returns 2 because $a is not defined.

PHP Ternary Operator Example


<?php
var_dump($a ?? 2);

// the expression inside var_dump is equal to following code
if (isset($a)) {
	return $a;
} else {
	return 2;
}

Run Example ››

Important: Null coalescing operator allows for nesting.

PHP Ternary Operator Nesting Example


<?php
$a = null;
$b = null;
$c = 5;
$d = 3;

var_dump($a ?? $b ?? $c ?? $d); // outputs 5

Run Example ››
Advertisement
2
176