最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - PHP alternative to ternary operator - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question asked Oct 26, 2011 at 9:50 ChaimChaim 2,1494 gold badges27 silver badges48 bronze badges 2
  • possible duplicate of Does PHP have a default assignment idiom like perl?, PHP Ternary operator clarification, How to set default value to a string in PHP if another string is empty? – outis Commented Apr 1, 2012 at 5:45
  • Does this answer your question? PHP short-ternary ("Elvis") operator vs null coalescing operator – trejder Commented Jul 23, 2023 at 17:47
Add a ment  | 

4 Answers 4

Reset to default 19

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

$var = $value or $var = $default;

Another fiddly workaround (patible 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 pact syntax alternative, just avoids mentioning $value twice.)

with 5.3 or without 5.3 I would write.

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

because I hate write-only constructs.

发布评论

评论列表(0)

  1. 暂无评论