检查数组是否为空

检查数组是否为空

本文介绍了如何使用 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']);

推荐答案

如果只需要检查数组中是否有ANY元素

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 explodeing weird strings):

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

这篇关于如何使用 PHP 检查数组是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:24