10

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

Timotheus Triebl
  • 1,466
  • 3
  • 18
  • 27
  • use oop PHP you can achieve this consider each case as a method name. – Sundar Jun 18 '14 at 13:05
  • 1
    That's as short as it's going to get while keeping your sanity. – Ja͢ck Jun 18 '14 at 13:05
  • There are TERNARY OPERATORS, they offer something like this (and I'm too lazy to write a full answer currently) :) – Sliq Jun 18 '14 at 13:05
  • dublicate of http://stackoverflow.com/questions/16026612/if-else-php-shorthand?rq=1 – h.s.o.b.s Jun 18 '14 at 13:06
  • there are so much duplicates of this that you can choose which one to pick, that is a duplicate of other, that is a dup of other, and so on.. – hlscalon Jun 18 '14 at 13:08
  • 1
    It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious. Source: http://us2.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary – Syed Qarib Jun 18 '14 at 13:12
  • 1
    Could you show a piece of code that warrants such a shorthand? – Ja͢ck Jun 18 '14 at 13:14

2 Answers2

38

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.

Ing. Michal Hudak
  • 4,460
  • 8
  • 53
  • 84
4

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.

Ilyas karim
  • 3,383
  • 3
  • 26
  • 40
fdehanne
  • 1,759
  • 1
  • 16
  • 27