玩家要么是空的,要么是逗号分隔的列表(或者是单个值)。检查它是否为空的最简单的方法是什么?我假设我可以这样做,只要我取回$gameresult数组到$gamerow?在这种情况下,如果$playerlist是空的,跳过爆炸可能会更有效,但为了讨论,我如何检查数组是否为空?
$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);
玩家要么是空的,要么是逗号分隔的列表(或者是单个值)。检查它是否为空的最简单的方法是什么?我假设我可以这样做,只要我取回$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。
数组为空。
其他回答
我已经用以下代码解决了这个问题。
$catArray=array();
$catIds=explode(',',$member['cat_id']);
if(!empty($catIds[0])){
foreach($catIds as $cat_id){
$catDetail=$this->Front_Category->get_category_detail($cat_id);
$catArray[]=$catDetail['allData']['cat_title'];
}
echo implode(',',$catArray);
}
我使用这个代码
$variable = array();
if( count( $variable ) == 0 )
{
echo "Array is Empty";
}
else
{
echo "Array is not Empty";
}
但请注意,如果数组有大量的键,与这里的其他答案相比,这段代码将花费大量时间来计算它们。
如果你想排除假行或空行(例如0 => "),在使用empty()将失败的情况下,你可以尝试:
if (array_filter($playerlist) == []) {
// Array is empty!
}
array_filter():如果没有提供回调,数组中所有等于FALSE的条目(参见转换为布尔值)将被删除。
如果你想删除所有NULL, FALSE和空字符串("),但保留零值(0),你可以使用strlen作为回调,例如:
$is_empty = array_filter($playerlist, 'strlen') == [];
如果你要检查数组内容,你可以使用:
$arr = array();
if(!empty($arr)){
echo "not empty";
}
else
{
echo "empty";
}
在这里看到的: http://codepad.org/EORE4k7v
如果你想确定你正在测试的变量是否实际上是一个空数组,你可以使用这样的东西:
if ($variableToTest === array()) {
echo 'this is explicitly an empty array!';
}