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 !

Community
  • 1
  • 1
QiMath
  • 455
  • 2
  • 7
  • 18

2 Answers2

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!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
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 ""

deChristo
  • 1,860
  • 2
  • 17
  • 29