shorthand php if{} ELSE IF{} else{}

Timotheus0106 picture Timotheus0106 · Jun 18, 2014 · Viewed 36.3k times · Source

is there a possibility to write a shorthand if, ELSE IF, else statement for php.

if / else is clear but is there a shorthanded way when i want to use elseif too (except switch)?

if ($typeArray == 'date'){
    echo 'date';
} else if($typeArray == 'time'){
    echo 'time';
} else {
    echo 'text';
}

Haven't found any good answer else, where there is a shorthand version for nested if statements including an elseif.

greetings timmi

Answer

Ing. Michal Hudak picture Ing. Michal Hudak · Jun 18, 2014

You're looking for ternary statements.

Syntax:

$condition ? $value_if_true : $value_if_false

Syntax for nested ternary statements:

$a ? $b : ( $c ? $d : ( $e ? $f : $g ) )

Just a warning, nested ternary statements are hard to read, so it's recommended to unnested ternary statements.