PHP shorthand for isset()?

PhpIssetShorthand

Php Problem Overview


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 | "";

Php Solutions


Solution 1 - Php

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the 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';

Solution 2 - Php

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

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

Or for all/older versions with isset:

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

or

!isset($var) && $var = '';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrentonstrineView Question on Stackoverflow
Solution 1 - Phphek2mglView Answer on Stackoverflow
Solution 2 - PhpFabien SaView Answer on Stackoverflow