5

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Is there any better or more concise way than following code to set default value of variables?

$v = isset($v) ? $v : "default value";
hakre
  • 193,403
  • 52
  • 435
  • 836
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173

5 Answers5

6

TL;DR - No, that expression can't be made any shorter.

What you want is for the shortened ternary expression to perform an implicit isset(). This has been discussed on the mailing list and an ifsetor RFC has been created that covers the concept as well.

Since the shortened ternary operator already existed at the time of the above discussion, something like this was proposed using a non-existent operator ??:

// PROPOSAL ONLY, DOES NOT WORK
$v = $v ?? 'default value';

Assign 'default value' if $v is undefined.

However, nothing like this has been implemented in the main language to date. Until then, what you have written can't be made any shorter.

This horrible construct is shorter, but note that it's not the same because it assigns the default value if the variable exists but evaluates to false:

// DO NOT USE
$v = @$v ?: 'default value';
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    What if `$v` is already set and it's `''` or `0` or `null` or `false`? – Carlos Nov 22 '12 at 07:46
  • 1
    @jackflash Hence my mention of "horrible construct" – Ja͢ck Nov 22 '12 at 07:49
  • This is not a good practice. So we can do like this - error_reporting( E_ALL & ~ E_NOTICE); echo $v = $v ?: 'default value'; This is same output as above. – som Nov 22 '12 at 08:12
  • @SoumyaBiswas I can't choose what is worse. – Carlos Nov 22 '12 at 08:17
  • @SoumyaBiswas Yes, that's right; the `@` does roughly the same, so the answer is really that it's not (practically) possible to make OP code shorter :) – Ja͢ck Nov 22 '12 at 08:17
  • Seems that this is my first controversial answer at SO; upvotes == downvotes :) – Ja͢ck Nov 22 '12 at 08:33
3

Here is a shorter syntax:

isset($v) || $v="default value";
Reza Salarmehr
  • 478
  • 3
  • 4
2

Just asked this and was pointed here. So in case you use a key of an array, this might be an improvement

function isset_get($array, $key, $default = null) {
    return isset($array[$key]) ? $array[$key] : $default;
}
Community
  • 1
  • 1
SunnyRed
  • 3,525
  • 4
  • 36
  • 57
0

Nope. That's the right way if you don't really know whether $v is set.

Carlos
  • 4,949
  • 2
  • 20
  • 37
0

No way.If you use ternary operator.

Echilon
  • 10,064
  • 33
  • 131
  • 217
som
  • 4,650
  • 2
  • 21
  • 36