3

I have troubles understanding how the php shorthands for if/else described here works.

<?=(expression) ? $foo : $bar?> 

The expression I'm trying to shorten is the following :

if (isset($result[1][0])) { $var = $result[1][0]; } else { $var = ""; } 

Can somebody explain me how I can apply the shorthand if/else statement in my situation ?

Thank you !

2 Answers 2

11

You can use ternary operator like this:

$var = (isset($result[1][0])) ? $result[1][0] : ""; 

See more about Ternary Operator

In case of PHP 7, you can do it like this:

$var = $result[1][0] ?? '' 

Hope this helps!

Sign up to request clarification or add additional context in comments.

6 Comments

Maybe add a closing parenthesis ?
PHP 7 can even make it shorter: $var = $result[1][0] ?? "";
Thank you for all theses quick answers, I wasn't even close... Unfortunately I'm not running PHP 7 at the moment so I'll go with this :) Thanks !
The parentheses around the isset expression aren't really necessary. It doesn't hurt to have them, but you don't need them.
@Don'tPanic - Yes the parenthesis isn't necessary but the code seems clean and understandable by using that parenthesis. So I prefer to use that parenthesis!
|
1

It's simple. Think of it as:

Condition ? Executes if condition is true : otherwise

In your case:

$var = isset($result[1][0]) ? $result[1][0] : ""; 

condition: isset($result[1][0])

if true: return $result[1][0]

else: return ""

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.