How to use the conditional and null coalesce operators

Examples that use the conditional operator

Set a string based on a comparison

       $message = ($age >= 18) ? 'Can vote' : 'Cannot vote';  // Ternary Operator
      

Set a variable depending on whether another variable is not null

       $greeting = (isset($first_name)) ? $first_name : 'Guest'; // Ternary Operator
      

Select a singular or plural ending based on a value

      $ending = ($error_count == 1) ? '' : 's'. // Ternary Operator
      $message = 'Found ' . $error_count . ' error' . $ending . '.'; 
      

Return one of two values based on a comparison

      return($number > $highest) ? $nuber : $highest;  // Ternary Operator
      

Bound a value within a fixed range

       $value = ($value < $max) ? $max : (($value > $min) ? $min : $value); // Ternary Operator
      

The first example rewritten with an if statement

      if ($age >= 18) {
        $message = 'Can vote';
      } else {
        $message = 'Cannot vote';
      } 
      

The fifth example rewritten with an if statement

      if ($value > $max) {
        $value = $max;
      } else if ($value > $min) {
        $value = $min;
      } 
      

Examples that use the null coalesce operator

Set a variable depending on whether another variable is not null

      $greeting = $first_name ?? 'Guest'; // Ternary Operator
      

Set a variable depending on whether multiple variables are not null

      $greeting = $first_name ?? $email_address ?? 'Guest';
      

Back