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

痞子三分冷 提交于 2020-01-01 04:17:30

问题


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 ($someEmptyString == "")
    $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!


回答1:


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';



回答2:


$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.




回答3:


You can use the ternary operator

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



回答4:


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



来源:https://stackoverflow.com/questions/6459171/how-to-set-default-value-to-a-string-in-php-if-another-string-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!