Skip to content

Instantly share code, notes, and snippets.

@rdp77
Last active August 11, 2022 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdp77/e05c5d9b00a5c4e2a3f6ffc70deb1ece to your computer and use it in GitHub Desktop.
Save rdp77/e05c5d9b00a5c4e2a3f6ffc70deb1ece to your computer and use it in GitHub Desktop.
short code if conditions with ternary operator
// ----------------------------------------------------------------
// If Conditions
// ----------------------------------------------------------------
if ($status == 'in review') ProductStatusEmailNotification::dispatch($product, Auth::user());
if ($expr) {
$statement;
} else {
$statement;
}
// ----------------------------------------------------------------
// Default Ternary Options
// ----------------------------------------------------------------
$result = $expr ? $statementTrue : $statementFalse;
// ----------------------------------------------------------------
// Non-obvious Ternary Behaviour
// ----------------------------------------------------------------
// on first glance, the following appears to output 'true'
echo (true ? 'true' : false ? 't' : 'f');
// however, the actual output of the above is 't' prior to PHP 8.0.0
// this is because ternary expressions are left-associative
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, one can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
// ----------------------------------------------------------------
// Short-ternary chaining
// ----------------------------------------------------------------
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE
$v = '';
echo ($v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
// ----------------------------------------------------------------
// Null Coalesce Operator
// ----------------------------------------------------------------
$action = $_POST['action'] ?? 'default';
$foo = null;
$bar = null;
$baz = 1;
$qux = 2;
echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment