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

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

当前回答

我使用这个代码

$variable = array();

if( count( $variable ) == 0 )
{
    echo "Array is Empty";
}
else
{
    echo "Array is not Empty";
}

但请注意,如果数组有大量的键,与这里的其他答案相比,这段代码将花费大量时间来计算它们。

其他回答

Count ($gamerow['players'])将为0。

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

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

为什么没有人回答:

$array = [];

if($array == []) {
    // array is empty
}
empty($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;在我看来,这是个坏主意。