玩家要么是空的,要么是逗号分隔的列表(或者是单个值)。检查它是否为空的最简单的方法是什么?我假设我可以这样做,只要我取回$gameresult数组到$gamerow?在这种情况下,如果$playerlist是空的,跳过爆炸可能会更有效,但为了讨论,我如何检查数组是否为空?

$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);

当前回答

您可以使用以下php函数来检查数组是否为空

使用empty()函数

$variable = array();
    if(empty($variable)){
    echo("The array is empty.");
    }

OUTPUT:数组为空

使用sizeof()函数

$variable = array();
$arraysize = sizeof($variable);
echo("The size of the array is $arraysize. \n");
if(sizeof($variable) == 0)
echo("The array is empty.");

输出:

数组的大小为0。

数组为空。

其他回答

我认为确定数组是否为空的最好方法是像这样使用count():

if(count($array)) {
    return 'anything true goes here';
}else {
    return 'anything false'; 
}

这似乎适用于所有情况

if(!empty(sizeof($array)))

如果你只需要检查数组中是否有任何元素,你可以使用数组本身,因为PHP的松散类型,或者-如果你喜欢更严格的方法-使用count():

if (!$playerlist) {
     // list is empty.
}
if (count($playerlist) === 0) {
     // list is empty.
}

如果你需要在检查之前清理空值(通常是为了防止奇怪的字符串爆炸):

foreach ($playerlist as $key => $value) {
    if (!strlen($value)) {
       unset($playerlist[$key]);
    }
}
if (!$playerlist) {
   //empty array
}
$status = "";

$new_array = array();

if(!empty($new_array)){
  $status = "1";   // not a blank array
}
else{
  $status = "0";   // blank array
}

为什么没有人回答:

$array = [];

if($array == []) {
    // array is empty
}