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

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

当前回答

在PHP中,空数组是错误的,因此甚至不需要像其他人建议的那样使用empty()。

<?php
$playerList = array();
if (!$playerList) {
    echo "No players";
} else {
    echo "Explode stuff...";
}
// Output is: No players

PHP的empty()确定变量是否存在或值是否为假值(如array(), 0, null, false等)。

在大多数情况下,你只想检查!$emptyVar。使用empty($emptyVar)如果变量可能没有设置,你不愿意触发一个E_NOTICE;在我看来,这是个坏主意。

其他回答

在我看来,索引数组的最简单的方法是:

    if ($array) {
      //Array is not empty...  
    }

如果数组不为空,则数组上的'if'条件将计算为true,如果数组为空则为false。这不适用于关联数组。

这似乎适用于所有情况

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

您可以使用以下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。

数组为空。

如果你只需要检查数组中是否有任何元素,你可以使用数组本身,因为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
}
empty($gamerow['players'])