How to check whether an array is empty using PHP?(如何使用 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 检查数组是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 PHP 检查数组是否为空?
基础教程推荐
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的foreach复选框POST 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- Web 服务器如何处理请求? 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
