Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shorthand php if{} ELSE IF{} else{} [duplicate]

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

like image 743
Timotheus0106 Avatar asked Jun 18 '14 13:06

Timotheus0106


People also ask

How do I shorten if else in PHP?

Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures.

What is if and else in PHP?

In PHP we have the following conditional statements: if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false.

What is shorthand if else?

Else (Ternary Operator) There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line.

Why conditional statements are used in PHP?

PHP allows you to choose what action to take based on the result of a condition. This condition can be anything you choose, and you can combine conditions to make actions that are more complicated.


2 Answers

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.

like image 118
Ing. Michal Hudak Avatar answered Sep 22 '22 14:09

Ing. Michal Hudak


You can see this Ternary operator. Good when you have an if/else, but bad readability if you do more.

Alternative syntax. This syntax is useful when you use html/php in the same code. It helps us to see the end of if/foreach/while...

switch/case. The best is probably to post some code to see if it could be shortened.

like image 43
fdehanne Avatar answered Sep 20 '22 14:09

fdehanne