PHP shorthand for isset()?

brentonstrine picture brentonstrine · Sep 4, 2013 · Viewed 106.7k times · Source

Is there a shorthand way to assign a variable to something if it doesn't exist in PHP?

if(!isset($var) {
  $var = "";
}

I'd like to do something like

$var = $var | "";

Answer

hek2mgl picture hek2mgl · Sep 4, 2013

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';