shorthand php if{} ELSE IF{} else{} [duplicate]
Asked Answered
R

2

14

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

Remark answered 18/6, 2014 at 13:3 Comment(7)
use oop PHP you can achieve this consider each case as a method name.Bouncy
That's as short as it's going to get while keeping your sanity.Orola
There are TERNARY OPERATORS, they offer something like this (and I'm too lazy to write a full answer currently) :)Hodometer
dublicate of https://mcmap.net/q/827059/-if-else-php-shorthand-duplicate?rq=1Aplanospore
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..Salvage
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: us2.php.net/manual/en/…Orsino
Could you show a piece of code that warrants such a shorthand?Orola
N
45

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.

Northumbrian answered 18/6, 2014 at 13:5 Comment(5)
Ugh, don't ever recommend nested ternary statements, that make code so hard to readCompound
@BrandonWamboldt It can make it hard to read, but it is what the OP is asking for.Tetrabrach
@Tetrabrach Yeah, but like the answer below, it's good to mention why it's bad to use, so people new to programming don't think it's good practice.Compound
@BrandonWamboldt That is definitely true.Tetrabrach
hmm yes this suddenly seems like bad idea :DMeridel
P
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.

Protoxide answered 18/6, 2014 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.