php 检查 Laravel 视图中是否为 null 和空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45243205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:05:52  来源:igfitidea点击:

Check if null and empty string in Laravel view

phplaravelif-statement

提问by i-faith

in my view I have to output separately the one that is nulland the one that is empty string

在我看来,我必须分别输出那个null和那个empty string

so i have this:

所以我有这个:

@if( $str->a == null)
... // do somethin
@endif

@if( $str->a == '')
... // do somethin
@endif

the problem is they the same result.

问题是它们的结果相同。

Thanks

谢谢

回答by Alexey Mezenin

In the comments you've said you only want to check if it is null. So, use is_null():

在您所说的评论中,您只想检查它是否是null. 所以,使用is_null()

@if (is_null($str->a))
    // do somethin
@endif

回答by Krishna Jonnalagadda

@if( !empty($str->a))
... // do somethin
@endif

This are consider for empty

这是考虑为空

The following things are considered to be empty:

以下内容被认为是空的:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

回答by Hiren Pipariya

You can try this

你可以试试这个

@isset($str->a)
    // $str->a is defined and is not null...
@endisset

@empty($str->a)
    // $str->a is "empty"...
@endempty

If Statements Laravel docs

如果语句 Laravel 文档

回答by Jim Wright

$str->acan't be null and ''at the same time. Have you tried @elseif?

$str->a不能同时为空''。你试过@elseif吗?

@if( is_null($str->a))
... // do somethin
@elseif( $str->a == '')
... // do somethin
@endif

actually, it should only shows the ones that is null and not the one that is empty.

实际上,它应该只显示空的而不是空的。

It sounds like you want to check if $str->ais a valid string or not. As suggested in comments by @GrumpyCrouton you can use empty().

听起来您想检查是否$str->a是有效字符串。正如@GrumpyCrouton 在评论中所建议的,您可以使用empty()

@if( empty($str->a))
... // do somethin
@endif