111

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 | "";
brentonstrine
  • 21,694
  • 25
  • 74
  • 120

2 Answers2

326

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';
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    Here is a link to new features of PHP7 (including null coalescing operator): http://php.net/manual/en/migration70.new-features.php – kurdtpage Dec 20 '16 at 22:19
  • 1
    In addition to assignment statements this operator can also be used in function arguments. – Andreas Bergström Jul 31 '17 at 13:17
  • You may want to use something like this https://stackoverflow.com/a/9555794/171318 – hek2mgl Aug 24 '17 at 06:51
  • 4
    @MakashovNurbol on my setup PHP 7.1.11 it works with arrays. – humanityANDpeace Oct 26 '17 at 14:19
  • 1
    php 7.0 doesn't work with arrays. upgrade if possible – user3791372 Dec 09 '17 at 12:26
  • so-called?... lol it's not "so-called" when it's actually called that. This answer is unnecessarily rude. – Sunhat Feb 22 '22 at 15:08
  • @Sunhat Thanks for showing me this, it was not my intention to be rude. fyi: I'm from Germany and made a translation error. Translated to German naively, `so-called` has a different, not rude meaning. It just means "a thing with name X" where X is a name supposed to be new to the reader. – hek2mgl Feb 22 '22 at 16:35
  • @Sunhat I've just checked a German-English language forum, people suggest "an operator which is known as X" instead of "so-called X". Again, thanks for showing me this. I must have made this 1000 times wrong before :) – hek2mgl Feb 22 '22 at 16:42
  • My apologies for that interpretation then!! - That's cool and interesting to know too! – Sunhat Feb 27 '22 at 00:58
73

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 = '';
Fabien Sa
  • 9,135
  • 4
  • 37
  • 44