Shorthand php if {} ELSE IF {} else {}

is it possible to write shorthand if, ELSE IF, else statement for php.

if / else is clear, but is there a shorthand way when I want to use elseif (other than the switch)?

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

They did not find a good else answer, where there is an abridged version for nested if statements, including elseif.

greetings timmi

+6
source share
2 answers

You are looking for ternary statements .

Syntax:

 $condition ? $value_if_true : $value_if_false 

The syntax for nested ternary operators is:

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

Just a warning, nested ternary statements are hard to read, so he recommended unhealthy ternary statements.

+21
source

You can see this Ternary statement . It’s good if you have if / else, but poor readability if you do more.

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

switch / case . It’s best to post some code to see if it can be shortened.

+3
source

Source: https://habr.com/ru/post/971009/


All Articles