如果另一个字符串为空,如何为 PHP 中的字符串设置默认值?
最好的例子是向您展示如何在 Javascript 中解决这个问题:
var someString = someEmptyString || 'new text value';
在这个 javascript 示例中,我们检测到“someEmptyString”为空,并自动将该值设置为“新文本值”。这在 PHP 中可能吗?最短的(代码)方法是什么?
这就是我现在的做法:
if ($someEmptyString == "")
$someString = 'new text value'; else $someString = $someEmptyString;
这困扰了我很长一段时间,如果有人知道更好的方法来做到这一点,我将非常感激。谢谢你!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 三元运算符
?:
< /a>.如果你有 PHP 5.3,这非常优雅:
在 5.3 之前,它需要更详细一点:
You can use the ternary operator
?:
.If you have PHP 5.3, this is very elegant:
Before 5.3, it needs to be a bit more verbose:
我认为这将是最正确的方法。检查该变量是否为空或者是否未设置并运行条件。
它仍然是一些代码,但是执行时您不应该收到任何 PHP 警告或错误。
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
虽然三元更清楚发生了什么,您也可以像这样设置变量
适用于所有 PHP 版本,您可以扩展它以轻松使用超过 1 个选项失败,
我个人认为这比其三元等效项更具可读性
While ternary is more clear whats happening, You can also set the variable like this
Works in all PHP versions, You can extend this to use more than 1 option failry easily also
which I personally find more readable than its ternary equivalent