Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Ruby you can easily set a default value for a variable

x ||= "default"

The above statement will set the value of x to "default" if x is nil or false

Is there a similar shortcut in PHP or do I have to use the longer form:

$x = (isset($x))? $x : "default";

Are there any easier ways to handle this in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

As of PHP 5.3 you can use the ternary operator while omitting the middle argument:

$x = $x ?: 'default';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...