如何使用PHP检查数组是否为空? [英] How to check whether an array is empty using PHP?
问题描述
players
将为空或用逗号分隔的列表(或单个值).检查它是否为空的最简单方法是什么?我以为只要将$gameresult
数组提取到$gamerow
中就可以这样做?在这种情况下,如果$playerlist
为空,则跳过爆炸可能会更有效,但是出于参数的考虑,我将如何检查数组是否也为空?
players
will either be empty or a comma separated list (or a single value). What is the easiest way to check if it's empty? I'm assuming I can do so as soon as I fetch the $gameresult
array into $gamerow
? In this case it would probably be more efficient to skip exploding the $playerlist
if it's empty, but for the sake of argument, how would I check if an array is empty as well?
$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);
推荐答案
如果只需要检查数组中是否有任何元素
If you just need to check if there are ANY elements in the array
if (empty($playerlist)) {
// list is empty.
}
如果您需要在检查之前清除空值(通常是为了防止explode
怪异字符串):
If you need to clean out empty values before checking (generally done to prevent explode
ing weird strings):
foreach ($playerlist as $key => $value) {
if (empty($value)) {
unset($playerlist[$key]);
}
}
if (empty($playerlist)) {
//empty array
}
这篇关于如何使用PHP检查数组是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!