开发者

How to set default value to a string in PHP if another string is empty?

Best example would be to show you how is this solved in Javascript:

var someString = someEmptyString || 'new text value';

In this javascript example, we have detected that 'someEmptyString' is empty and automatically set the value to 'new text value'. Is this possible in PHP and what's the shortest (code) way to do it?

This is how I do it now:

if ($someEmpty开发者_如何学PythonString == "")
    $someString = 'new text value'; else $someString = $someEmptyString;

This is bugging me for quite some time and I would be very grateful if someone knows a better way to do this. Thank you!


You can use the ternary operator ?:.

If you have PHP 5.3, this is very elegant:

$someString = $someEmptyString ?: 'new text value';

Before 5.3, it needs to be a bit more verbose:

$someString = $someEmptyString ? $someEmptyString : 'new text value';


$someString = (!isSet( $someEmptyString ) || empty( $someEmptyString ) )? "new text value" : $someEmptyString;

I think that would be the most correct way to do this. Check if that var is empty or if it's not set and run condition.

it's still a bit of code, but you shouldn't get any PHP warnings or errors when executed.


You can use the ternary operator

$someString = $someEmptyString ?: "New Text Value";


While ternary is more clear whats happening, You can also set the variable like this

($someString = $someEmptyString) || ($someString = "Default");

Works in all PHP versions, You can extend this to use more than 1 option failry easily also

($someString = $someEmptyString) ||
($someString = $someOtherEmptyString) ||
($someString = "Default");

which I personally find more readable than its ternary equivalent

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜