short ternary operator code example

Example 1: php ternary

$result = $condition ? 'foo' : 'bar';

Example 2: php ternary operators

// Both ternary and if/else returns the same result

// ternary
$result = $condition ? 'foo' : 'bar';

// if/else
if ($condition) {
    $result = 'foo' 
} else {
    $result = 'bar'
}

Example 3: ternary operator

(condition) ? (if true, do this) : (otherwise, do this)

Example 4: ternary operator

// (condition) ? (if true, do this) : (otherwise, do this)
const hasAccount = true
// let userDisplayMessage
// if (hasAccount) {
//   userDisplayMessage = 'Welcome Back'
// } else {
//   userDisplayMessage = 'Please Sign Up'
// }
const userDisplayMessage = hasAccount ? 'Welcome Back' : 'Please Sign Up'
console.log(userDisplayMessage)

Example 5: Ternary Operator

condition ? expression-if-true : expression-if-false;

function findGreater(a, b) {
  return a > b ? "a is greater" : "b is greater";
}

Example 6: ternary operator

isMember ? '$2.00' : '$10.00'
// isMember true =>  output: "$2.00"

// isMember false =>  output: "$10.00"

// isMember null =>  output: "$10.00"

Tags:

C Example