如果另一个字符串为空,如何在PHP中将字符串的默认值设置为? [英] How to set default value to a string in PHP if another string is empty?

查看:825
本文介绍了如果另一个字符串为空,如何在PHP中将字符串的默认值设置为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好的例子是向您展示如何在Javascript中解决这个问题:

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

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

在这个javascript示例中,我们检测到'someEmptyString'为空并自动将值设置为'新文本值'。在PHP中这是可能的吗?最简单的(代码)方法是什么?

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!

推荐答案

你可以使用三元运算符?:

You can use the ternary operator ?:.

如果你有PHP 5.3,这是非常优雅的:

If you have PHP 5.3, this is very elegant:

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

在5.3之前,需要更详细一点:

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

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

这篇关于如果另一个字符串为空,如何在PHP中将字符串的默认值设置为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆