PHP if语句测试和存储

Mar*_*rio 1 php if-statement

首先抱歉标题 - 我不知道如何把它变得更好......我需要测试是否有空字符串,如果它不是我想存储它.我有这样的事情:

if (getStringBetween($array[0], "house", "dog") <> '') {
   $text = getStringBetween($array[0], "house", "dog");
}
Run Code Online (Sandbox Code Playgroud)

它可以缩短,所以我不重复这个getStringBetween($ array [0],"house","dog")两次.

我知道我可以这样做:

$a = getStringBetween($array[0], "house", "dog");
if ($a <> '') {
   $text = $a;
}
Run Code Online (Sandbox Code Playgroud)

但这是最好的方法吗?可以在不存储这个"额外"$变量的情况下完成吗?

谢谢!

Riz*_*123 6

你可以这样做:

$text = (getStringBetween($array[0], "house", "dog") != ""?getStringBetween($array[0], "house", "dog"):NULL);
Run Code Online (Sandbox Code Playgroud)

如果返回值getStringBetween()不等于空字符串,则为其分配,否则为NULL得分,因此未设置变量.(顺便说一句:我用的是!=代替<>,因为你在php中没有经常看到这种情况,很可能是在SQL中)

此外,我认为这是在保存代码和使其不可读之间的边界.因此,您决定使用哪一个.