PHP Laravel 检查数组是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52327744/
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-09-14 18:02:46  来源:igfitidea点击:

PHP Laravel Check if Array is empty

phplaravel

提问by Srima

I am struggling with displaying some content depending on if an array does have a value or not.Every time the code in the else part is executed. What's wrong here? Is there any syntax error with this code? I'm using php laravel.

我正在努力根据数组是否有值来显示一些内容。每次执行 else 部分中的代码时。这里有什么问题?这段代码有语法错误吗?我正在使用 php laravel。

foreach($now as $v)
{
        $arry[$c++]=$v->Code; 
}
if($arry==null){
     Do Something
}
else{
     Do Something else
}

回答by Sand Of Vega

if($arry) {
     echo 'The array is not empty';
}
else {
     echo 'The array is empty';
}

For more: How can you check if an array is empty?

更多信息:如何检查数组是否为空?

回答by Manoj Negi

if (sizeof($arry) > 0) Do Something else Do Something else

if (sizeof($arry) > 0) 做点别的做点别的

回答by Aleksandrs

Better to do if (!empty($arry)) {}

最好做 if (!empty($arry)) {}

P.S. yes if (!$arry)do the same, but every person which is not familiar with php or even have little understanding of programming, should understand the code. Whats mean "not array", but if it will be "not empty array" is more clear. It is very straight forward.

PS 是的if (!$arry)也一样,但是每个不熟悉php甚至对编程知之甚少的人都应该了解代码。什么是“非数组”,但如果它是“非空数组”就更清楚了。这是非常直接的。

Clean code

干净的代码

回答by Raghbendra Nayak

Always check array before iterate in foreach and check with count function to check its value

在 foreach 中迭代之前始终检查数组并检查计数函数以检查其值

if(isset($now) && count($now)>0){
    foreach($now as $v) {
            $arry[$c++]=$v->Code; 
    }
}
if(count($arry)>0){
     Do Something
}
else{
     Do Something else
}

回答by Nisfan

this is not related to Laravel framework

这与 Laravel 框架无关

if (count($arry) > 0) 
   Do Something
else
   Do Something else

回答by Jay Teli

You can use empty()or count()or sizeof()as below :

您可以使用empty()count()sizeof()如下:

$a = [];
if(empty($a)) {
    echo 'empty' . PHP_EOL;
} else {
    echo '!empty' . PHP_EOL;
}
if(count($a) == 0) {
    echo 'empty' . PHP_EOL;
} else {
    echo '!empty' . PHP_EOL;
}
if(sizeof($a) == 0) {
    echo 'empty' . PHP_EOL;
} else {
    echo '!empty' . PHP_EOL;
}

echo empty($a) . PHP_EOL; // 1
echo count($a) . PHP_EOL; // 0
echo sizeof($a) . PHP_EOL; // 0

Output : 
empty
empty
empty
1
0
0