Showing posts with label ternary operator. Show all posts
Showing posts with label ternary operator. Show all posts

Wednesday, 14 April 2021

Php: Ternary operator

Returns one of two expressions depending on a condition.

 

Syntax

expression ? expression1 : expression2

 

Returns expression1 if the 'expression' evaluates to true other wise returns expression 2.

 

Example

$msg1 = ($a % 2 == 0) ? "Even number" : "Odd number";

 

ternary_operator_demo.php

#!/usr/bin/php

<?php
$a = 10;
$b = 11;

$msg1 = ($a % 2 == 0) ? "Even number" : "Odd number";
$msg2 = ($b % 2 == 0) ? "Even number" : "Odd number";

echo "$a is $msg1\n";
echo "$b is $msg2";
?>

 

Output

$./ternary_operator_demo.php 

10 is Even number
11 is Odd number

 

 

 

 

  

Previous                                                    Next                                                    Home

Friday, 26 July 2019

Processing: Ternary operator


Ternary operator( ?: )
   Returns one of two expressions depending on a condition.

    Syntax
       test ? expression1 : expression2
Returns expression1 if the “test” condition evaluates to true other wise returns expression 2.

Operators.pde
int a = 100;

int flag = a>10 ? 1 : 0;
println(flag);

flag = a>1000 ? 1 : 0;
println(flag);


Output
1
0

Observation
See the statement “flag = a>10 ? 1 : 0”, a>10 is true, so 1 is returned and assigned to the flag,

Previous                                                    Next                                                    Home

Sunday, 13 January 2019

Groovy: Ternary operator (?:)


It is a short cut to if-else statement.

Syntax
value = (expression) ? statement1 : statement2

If the expression is evaluated to true, then statement1 is assigned to the value, else statement2 is assigned to the value.

HelloWorld.groovy
a = 10

message = (a == 10) ? "a is equal to 10" : "a is not equal to 10"

println message

Output
a is equal to 10

Previous                                                 Next                                                 Home