php 检查数组是否为空

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

Check if array is empty

phparraysif-statement

提问by user1684586

The following code shows an array of records in the $rowsarray from the MySQL query. I have added also an ifstatement to check if $rowsturns up empty, but it is not working.

以下代码显示了$rows来自 MySQL 查询的数组中的记录数组。我还添加了一个if语句来检查是否$rows为空,但它不起作用。

$rows = array();

$result1 = mysql_query("SELECT * FROM TestPhase where Pid<10", $db) or die("cannot select");
while($row = mysql_fetch_array($result1)) {
  $rows []= array(
    'id' => $row['id'],
    'parent' => $row['parent'],
    'name' => $row['name'],
  );

}


if($rows == ""){
    echo "No Data";

    }

This ifstatement is not working. How do I check if the array returns empty and echo "No Data".

if语句不起作用。如何检查数组是否返回空并回显“无数据”。

How would I check to see if the array is empty in javascript? I have placed the $rowsarray in a var treeData.

我将如何检查javascript中的数组是否为空?我已将$rows数组放在一个var treeData.

if (treeData) is empty{
$("button").hide();
     }

How do I check if treeDatais empty to hide the button.

如何检查是否treeData为空以隐藏按钮。

回答by Havelock

PHP
Simply use empty(), i.e.

PHP
简单使用empty(),即

if(empty($rows)){
    echo 'No Data';
}

Alternatively you could also use count(), i.e.

或者你也可以使用count(),即

if(count($rows) < 1){ // or if(count($rows) === 0)
    echo 'No Data';
}

JavaScript
You can use the lengthproperty

JavaScript
您可以使用该length属性

if(treeData.length == 0){
    $("button").hide();
}

回答by Muthu Kumaran

Use countto check

使用count来检查

if(!count($rows)){
    echo "No Data";
}

Using JavaScript, here is the example

使用 JavaScript,这里是示例

var arr = new Array('one', 'two', 'three'); //assume you have list of values in array
if(!arr.length){ //if no array value exist, show alert()
   alert('No Data');
}

回答by BenM

You can't treat an array like a string (i.e. $rows == ""). Use count()or empty()instead:

您不能将数组视为字符串(即$rows == "")。使用count()empty()代替:

if(count($rows) == 0)
{
    echo "No Data";
}

回答by moonwave99

Use empty:

使用empty

if( empty( $rows) ) { ... }

回答by Gustav Barkefors

if ( count( $rows ) == 0 ) {...}