6

In JavaScript you can use the following code:

var = value || default;

Is there an equivalent in PHP except for the ternary operator:

$var = ($value) ? $value : $default;

The difference being only having to write $value once?

Chaim
  • 2,109
  • 4
  • 27
  • 48
  • possible duplicate of [Does PHP have a default assignment idiom like perl?](http://stackoverflow.com/q/2958630/90527), [PHP Ternary operator clarification](http://stackoverflow.com/q/3580461/), [How to set default value to a string in PHP if another string is empty?](http://stackoverflow.com/q/6459171/90527) – outis Apr 01 '12 at 05:45
  • Does this answer your question? [PHP short-ternary ("Elvis") operator vs null coalescing operator](https://stackoverflow.com/questions/34571330/php-short-ternary-elvis-operator-vs-null-coalescing-operator) – trejder Jul 23 '23 at 17:47

4 Answers4

19

Since of php 5.3 $var = $value ?: $default

vsushkov
  • 2,445
  • 1
  • 19
  • 28
  • Thanks, only issue is that Dreamweaver doesn't recognize this as valid code so I'm left with an error on that line. The PHP processor does, so I suppose that's what counts... – Chaim Oct 26 '11 at 09:55
5
$var = $value or $var = $default;
dmitry
  • 4,989
  • 5
  • 48
  • 72
1

Another fiddly workaround (compatible with pre-5.3) would be:

$var = current(array_filter(array($value, $default, $default2)));

But that's really just advisable if you do have multiple possible values or defaults. (Doesn't really save on typing, not a compact syntax alternative, just avoids mentioning $value twice.)

mario
  • 144,265
  • 20
  • 237
  • 291
  • Thanks, essentially I was looking for a way to save on typing (and to add a little more readability) – Chaim Oct 26 '11 at 11:01
0

with 5.3 or without 5.3 I would write.

$var = 'default';
if ($value) $var = $value;

because I hate write-only constructs.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345