玩家要么是空的,要么是逗号分隔的列表(或者是单个值)。检查它是否为空的最简单的方法是什么?我假设我可以这样做,只要我取回$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的松散类型,或者-如果你喜欢更严格的方法-使用count():
if (!$playerlist) {
// list is empty.
}
if (count($playerlist) === 0) {
// list is empty.
}
如果你需要在检查之前清理空值(通常是为了防止奇怪的字符串爆炸):
foreach ($playerlist as $key => $value) {
if (!strlen($value)) {
unset($playerlist[$key]);
}
}
if (!$playerlist) {
//empty array
}
在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;在我看来,这是个坏主意。
如果你要检查数组内容,你可以使用:
$arr = array();
if(!empty($arr)){
echo "not empty";
}
else
{
echo "empty";
}
在这里看到的: http://codepad.org/EORE4k7v
一些不错的答案,但我只是想展开一点,以更清楚地解释PHP何时确定数组是否为空。
主要记录:
带有一个键(或多个键)的数组将被PHP判定为非空。
由于数组值需要键才能存在,数组中是否有值并不决定数组是否为空,只有在没有键(因此也没有值)的情况下才会决定数组是否为空。
因此,用empty()检查数组并不只是告诉你是否有值,而是告诉你数组是否为空,键是数组的一部分。
因此,在决定使用哪种检查方法之前,请考虑如何生成数组。 当用户提交HTML表单时,当每个表单字段都有一个数组名称(即name="array[]"),数组就会有键。 将为每个字段生成一个非空数组,因为每个表单字段的数组将有自动递增的键值。
以这些数组为例:
/* Assigning some arrays */
// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");
// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";
// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';
如果你回显上述数组的数组键和值,你会得到以下结果:
一号阵: [UserKeyA] => [UserValueA] [UserKeyB] => [UserValueB] 二阵: [0] => [UserValue01] [1] => [UserValue02] 三阵: [0] => [] [1] => []
并且用empty()测试上述数组会返回以下结果:
数组: $ArrayOne不是空的 两个数组: $ArrayTwo不是空的 组三: $ArrayThree不是空的
当你赋值一个数组但之后不使用它时,数组将始终为空,例如:
$ArrayFour = array();
这将是空的,即PHP在上面使用if empty()时将返回TRUE。
因此,如果你的数组有键-例如通过表单的输入名称或如果你手动分配它们(即创建一个数据库列名作为键的数组,但没有数据库中的值/数据),那么数组将不是空的()。
在这种情况下,您可以在foreach中循环数组,测试每个键是否有一个值。如果您无论如何都需要遍历数组,比如检查键或清除数据,这是一个好方法。
然而,如果你只是需要知道“值是否存在”返回TRUE或FALSE,这不是最好的方法。 当一个数组知道它将有键时,有各种方法来确定它是否有值。函数或类可能是最好的方法,但它总是取决于您的环境和确切的需求,以及其他事情,例如您当前如何处理数组(如果有的话)。
下面是一种方法,它使用很少的代码来检查数组是否有值:
使用array_filter (): 遍历数组中的每个值,将它们传递给回调函数。如果回调函数返回true,则数组中的当前值返回到结果数组中。数组键被保留。
$EmptyTestArray = array_filter($ArrayOne);
if (!empty($EmptyTestArray))
{
// do some tests on the values in $ArrayOne
}
else
{
// Likely not to need an else,
// but could return message to user "you entered nothing" etc etc
}
在所有三个示例数组上运行array_filter()(在这个答案的第一个代码块中创建),结果如下:
数组: $arrayone不是空的 两个数组: $arraytwo不是空的 组三: $arraythree为空
因此,当没有值时,无论是否有键,使用array_filter()创建一个新数组,然后检查新数组是否为空,显示原始数组中是否有任何值。 这并不理想,而且有点混乱,但如果您有一个巨大的数组,并且由于任何其他原因不需要循环它,那么就所需的代码而言,这是最简单的。
我在检查开销方面没有经验,但如果能知道使用array_filter()和foreach检查是否找到值之间的区别,那就更好了。
显然,基准测试需要在各种参数上,在大小数组上,当有值时,等等。
我使用这个代码
$variable = array();
if( count( $variable ) == 0 )
{
echo "Array is Empty";
}
else
{
echo "Array is not Empty";
}
但请注意,如果数组有大量的键,与这里的其他答案相比,这段代码将花费大量时间来计算它们。
如果你想确定你正在测试的变量是否实际上是一个空数组,你可以使用这样的东西:
if ($variableToTest === array()) {
echo 'this is explicitly an empty array!';
}
$gamerow = mysql_fetch_array($gameresult);
if (!empty(($gamerow['players'])) {
$playerlist = explode(",", $gamerow['players']);
}else{
// do stuff if array is empty
}
你可以使用array_filter(),它适用于所有情况:
$ray_state = array_filter($myarray);
if (empty($ray_state)) {
echo 'array is empty';
} else {
echo 'array is not empty';
}
我认为确定数组是否为空的最好方法是像这样使用count():
if(count($array)) {
return 'anything true goes here';
}else {
return 'anything false';
}
我已经用以下代码解决了这个问题。
$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);
}
如果你想排除假行或空行(例如0 => "),在使用empty()将失败的情况下,你可以尝试:
if (array_filter($playerlist) == []) {
// Array is empty!
}
array_filter():如果没有提供回调,数组中所有等于FALSE的条目(参见转换为布尔值)将被删除。
如果你想删除所有NULL, FALSE和空字符串("),但保留零值(0),你可以使用strlen作为回调,例如:
$is_empty = array_filter($playerlist, 'strlen') == [];
在我看来,索引数组的最简单的方法是:
if ($array) {
//Array is not empty...
}
如果数组不为空,则数组上的'if'条件将计算为true,如果数组为空则为false。这不适用于关联数组。
我运行了文章末尾包含的基准测试。比较方法:
Count ($arr) == 0:计数 Empty ($arr):空 $arr == []: comp (bool) $arr:类型转换
得到了以下结果
Contents \method | count | empty | comp | cast |
------------------|--------------|--------------|--------------|--------------|
Empty |/* 1.213138 */|/* 1.070011 */|/* 1.628529 */| 1.051795 |
Uniform |/* 1.206680 */| 1.047339 |/* 1.498836 */|/* 1.052737 */|
Integer |/* 1.209668 */|/* 1.079858 */|/* 1.486134 */| 1.051138 |
String |/* 1.242137 */| 1.049148 |/* 1.630259 */|/* 1.056610 */|
Mixed |/* 1.229072 */|/* 1.068569 */|/* 1.473339 */| 1.064111 |
Associative |/* 1.206311 */| 1.053642 |/* 1.480637 */|/* 1.137740 */|
------------------|--------------|--------------|--------------|--------------|
Total |/* 7.307005 */| 6.368568 |/* 9.197733 */|/* 6.414131 */|
empty和强制转换为布尔类型的区别是没有意义的。我已经多次运行这个测试,它们看起来基本上是相同的。数组的内容似乎没有发挥重要作用。这两者产生了相反的结果,但逻辑上的否定几乎不足以推动施法在大多数情况下获胜,所以我个人更喜欢空,因为在任何一种情况下都是易读的。
#!/usr/bin/php
<?php
// 012345678
$nt = 90000000;
$arr0 = [];
$arr1 = [];
$arr2 = [];
$arr3 = [];
$arr4 = [];
$arr5 = [];
for ($i = 0; $i < 500000; $i++) {
$arr1[] = 0;
$arr2[] = $i;
$arr3[] = md5($i);
$arr4[] = $i % 2 ? $i : md5($i);
$arr5[md5($i)] = $i;
}
$t00 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr0) == 0;
}
$t01 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr0);
}
$t02 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr0 == [];
}
$t03 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr0;
}
$t04 = microtime(true);
$t10 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr1) == 0;
}
$t11 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr1);
}
$t12 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr1 == [];
}
$t13 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr1;
}
$t14 = microtime(true);
/* ------------------------------ */
$t20 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr2) == 0;
}
$t21 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr2);
}
$t22 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr2 == [];
}
$t23 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr2;
}
$t24 = microtime(true);
/* ------------------------------ */
$t30 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr3) == 0;
}
$t31 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr3);
}
$t32 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr3 == [];
}
$t33 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr3;
}
$t34 = microtime(true);
/* ------------------------------ */
$t40 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr4) == 0;
}
$t41 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr4);
}
$t42 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr4 == [];
}
$t43 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr4;
}
$t44 = microtime(true);
/* ----------------------------------- */
$t50 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr5) == 0;
}
$t51 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr5);
}
$t52 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr5 == [];
}
$t53 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr5;
}
$t54 = microtime(true);
/* ----------------------------------- */
$t60 = $t00 + $t10 + $t20 + $t30 + $t40 + $t50;
$t61 = $t01 + $t11 + $t21 + $t31 + $t41 + $t51;
$t62 = $t02 + $t12 + $t22 + $t32 + $t42 + $t52;
$t63 = $t03 + $t13 + $t23 + $t33 + $t43 + $t53;
$t64 = $t04 + $t14 + $t24 + $t34 + $t44 + $t54;
/* ----------------------------------- */
$ts0[1] = number_format(round($t01 - $t00, 6), 6);
$ts0[2] = number_format(round($t02 - $t01, 6), 6);
$ts0[3] = number_format(round($t03 - $t02, 6), 6);
$ts0[4] = number_format(round($t04 - $t03, 6), 6);
$min_idx = array_keys($ts0, min($ts0))[0];
foreach ($ts0 as $idx => $val) {
if ($idx == $min_idx) {
$ts0[$idx] = " $val ";
} else {
$ts0[$idx] = "/* $val */";
}
}
$ts1[1] = number_format(round($t11 - $t10, 6), 6);
$ts1[2] = number_format(round($t12 - $t11, 6), 6);
$ts1[3] = number_format(round($t13 - $t12, 6), 6);
$ts1[4] = number_format(round($t14 - $t13, 6), 6);
$min_idx = array_keys($ts1, min($ts1))[0];
foreach ($ts1 as $idx => $val) {
if ($idx == $min_idx) {
$ts1[$idx] = " $val ";
} else {
$ts1[$idx] = "/* $val */";
}
}
$ts2[1] = number_format(round($t21 - $t20, 6), 6);
$ts2[2] = number_format(round($t22 - $t21, 6), 6);
$ts2[3] = number_format(round($t23 - $t22, 6), 6);
$ts2[4] = number_format(round($t24 - $t23, 6), 6);
$min_idx = array_keys($ts2, min($ts2))[0];
foreach ($ts2 as $idx => $val) {
if ($idx == $min_idx) {
$ts2[$idx] = " $val ";
} else {
$ts2[$idx] = "/* $val */";
}
}
$ts3[1] = number_format(round($t31 - $t30, 6), 6);
$ts3[2] = number_format(round($t32 - $t31, 6), 6);
$ts3[3] = number_format(round($t33 - $t32, 6), 6);
$ts3[4] = number_format(round($t34 - $t33, 6), 6);
$min_idx = array_keys($ts3, min($ts3))[0];
foreach ($ts3 as $idx => $val) {
if ($idx == $min_idx) {
$ts3[$idx] = " $val ";
} else {
$ts3[$idx] = "/* $val */";
}
}
$ts4[1] = number_format(round($t41 - $t40, 6), 6);
$ts4[2] = number_format(round($t42 - $t41, 6), 6);
$ts4[3] = number_format(round($t43 - $t42, 6), 6);
$ts4[4] = number_format(round($t44 - $t43, 6), 6);
$min_idx = array_keys($ts4, min($ts4))[0];
foreach ($ts4 as $idx => $val) {
if ($idx == $min_idx) {
$ts4[$idx] = " $val ";
} else {
$ts4[$idx] = "/* $val */";
}
}
$ts5[1] = number_format(round($t51 - $t50, 6), 6);
$ts5[2] = number_format(round($t52 - $t51, 6), 6);
$ts5[3] = number_format(round($t53 - $t52, 6), 6);
$ts5[4] = number_format(round($t54 - $t53, 6), 6);
$min_idx = array_keys($ts5, min($ts5))[0];
foreach ($ts5 as $idx => $val) {
if ($idx == $min_idx) {
$ts5[$idx] = " $val ";
} else {
$ts5[$idx] = "/* $val */";
}
}
$ts6[1] = number_format(round($t61 - $t60, 6), 6);
$ts6[2] = number_format(round($t62 - $t61, 6), 6);
$ts6[3] = number_format(round($t63 - $t62, 6), 6);
$ts6[4] = number_format(round($t64 - $t63, 6), 6);
$min_idx = array_keys($ts6, min($ts6))[0];
foreach ($ts6 as $idx => $val) {
if ($idx == $min_idx) {
$ts6[$idx] = " $val ";
} else {
$ts6[$idx] = "/* $val */";
}
}
echo " | count | empty | comp | cast |\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo " Empty |";
echo $ts0[1] . '|';
echo $ts0[2] . '|';
echo $ts0[3] . '|';
echo $ts0[4] . "|\n";
echo " Uniform |";
echo $ts1[1] . '|';
echo $ts1[2] . '|';
echo $ts1[3] . '|';
echo $ts1[4] . "|\n";
echo " Integer |";
echo $ts2[1] . '|';
echo $ts2[2] . '|';
echo $ts2[3] . '|';
echo $ts2[4] . "|\n";
echo " String |";
echo $ts3[1] . '|';
echo $ts3[2] . '|';
echo $ts3[3] . '|';
echo $ts3[4] . "|\n";
echo " Mixed |";
echo $ts4[1] . '|';
echo $ts4[2] . '|';
echo $ts4[3] . '|';
echo $ts4[4] . "|\n";
echo " Associative |";
echo $ts5[1] . '|';
echo $ts5[2] . '|';
echo $ts5[3] . '|';
echo $ts5[4] . "|\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo " Total |";
echo $ts6[1] . '|';
echo $ts6[2] . '|';
echo $ts6[3] . '|';
echo $ts6[4] . "|\n";
做出最恰当的决策需要了解数据的质量以及要遵循的流程。
如果你要取消/忽略/删除这一行,那么最早的过滤点应该在mysql查询中。
哪里玩家不是空的 哪里的玩家!= " WHERE COALESCE(玩家,")!= " 哪里的球员不是NULL和球员!= " ...这取决于你的存储数据,还有其他方法,我就讲到这里。
If you aren't 100% sure if the column will exist in the result set, then you should check that the column is declared. This will mean calling array_key_exists(), isset(), or empty() on the column. I am not going to bother delineating the differences here (there are other SO pages for that breakdown, here's a start: 1, 2, 3). That said, if you aren't in total control of the result set, then maybe you have over-indulged application "flexibility" and should rethink if the trouble of potentially accessing non-existent column data is worth it. Effectively, I am saying that you should never need to check if a column is declared -- ergo you should never need empty() for this task. If anyone is arguing that empty() is more appropriate, then they are pushing their own personal opinion about expressiveness of scripting. If you find the condition in #5 below to be ambiguous, add an inline comment to your code -- but I wouldn't. The bottom line is that there is no programmatical advantage to making the function call. Might your string value contain a 0 that you want to deem true/valid/non-empty? If so, then you only need to check if the column value has length.
下面是一个使用strlen()的演示。这将指示字符串是否会在分解时创建有意义的数组元素。
I think it is important to mention that by unconditionally exploding, you are GUARANTEED to generate a non-empty array. Here's proof: Demo In other words, checking if the array is empty is completely useless -- it will be non-empty every time. If your string will NOT POSSIBLY contain a zero value (because, say, this is a csv consisting of ids which start from 1 and only increment), then if ($gamerow['players']) { is all you need -- end of story. ...but wait, what are you doing after determining the emptiness of this value? If you have something down-script that is expecting $playerlist, but you are conditionally declaring that variable, then you risk using the previous row's value or again generating Notices. So do you need to unconditionally declare $playerlist as something? If there are no truthy values in the string, does your application benefit from declaring an empty array? Chances are, the answer is yes. In this case, you can ensure that the variable is array-type by falling back to an empty array -- this way it won't matter if you feed that variable into a loop. The following conditional declarations are all equivalent.
If ($gamerow['players']) {$playerlist =爆炸(',',$gamerow['players']);} else {$playerlist = [];} $playerlist = $gamerow['玩家']?explosion (',', $gamerow['players']): [];
为什么我要花这么长时间来解释这个非常基本的任务?
I have whistleblown nearly every answer on this page and this answer is likely to draw revenge votes (this happens often to whistleblowers who defend this site -- if an answer has downvotes and no comments, always be skeptical). I think it is important that Stackoverflow is a trusted resource that doesn't poison researchers with misinformation and suboptimal techniques. This is how I show how much I care about upcoming developers so that they learn the how and the why instead of just spoon-feeding a generation of copy-paste programmers. I frequently use old pages to close new duplicate pages -- this is the responsibility of veteran volunteers who know how to quickly find duplicates. I cannot bring myself to use an old page with bad/false/suboptimal/misleading information as a reference because then I am actively doing a disservice to a new researcher.
$status = "";
$new_array = array();
if(!empty($new_array)){
$status = "1"; // not a blank array
}
else{
$status = "0"; // blank array
}
已经讨论了许多检查数组是否为空或不包含值的选项
If ($playerlist) {}
If (!empty($playerlist)) {}
If (count($playerlist) > 0) {}
各有利弊。
但还有另一种选择,如果你确定,你的数组只有数字键,从0开始(即,这发生在你爆炸()一个字符串):
if (isset($playerlist[0])) {
// do something
}
这甚至比其他解还要快一点。
您可以使用以下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。
数组为空。
Array_filter递归和计数
function array_filter_recursive(array $arr)
{
array_walk($arr,function(&$item){if (is_array($item)) { $item = array_filter_recursive($item);}});
return array_filter($arr);
}
function is_empty_array(array $arr):bool{
return count(array_filter_recursive($arr)) == 0;
}
test
$c=['b'=>2,'c'=>3];
$a=[];
$b=[[]];
$d=['a'=>[]];
$e=['a'=>[],[]];
$f=['a'=>[[],[],[]],[]];
$g=[[[],[[],[[],[[],[]]]]],[]];
$i=[[[],[[],[[],[[],['s'=>1]]]]],[]];
var_dump(is_empty_array($c));//false
var_dump(is_empty_array($a));//true
var_dump(is_empty_array($b));//true
var_dump(is_empty_array($d));//true
var_dump(is_empty_array($e));//true
var_dump(is_empty_array($f));//true
var_dump(is_empty_array($g));//true
var_dump(is_empty_array($i));//false
我不会重复这里已经说过的话,只是在PHP-7.3上测试和更有效的方法是!empty($myARR)或isset($myARR[0]),两者显示相同的速度。其他的都比较慢,包括array_key_exists($myARR[0])和比较$myARR !== Array() | $myARR !==[]。所以,我更喜欢empty(),简单快捷。