确定数组中有多少连续字段为空
I have an array with variables like: $shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");
Each field in this array represents a weekday.
I need to determine how many consecutive fields are empty depending on the day ("starting field").
For example:
If the start is $shippingtimearr[5]
it should return 3
since next "Monday" ($shippingtimearr[0]
) is NULL
.
If the start is an array value that is not NULL
, it should return 0
;
I tried creating a "for" loop like this:
for( $i = 2; $shippingtimearr[$i] = 0; $i++ ) {
$counter++;
}
But it didn't work and obviously, this would not account for the fact that a "week" should be looped again to see if the first days next week are "NULL
".
我有一个包含变量的数组: 我尝试创建一个“for”循环: p>
但它没有用,显然,这不会说明这一事实 应该再次循环“周”以查看下周的第一天是否为“ $ shippingtimearr = array(“”,“1630 “,”1530“,”1530“,”1530“,”“,”“”; code>
此数组中的每个字段代表一个工作日。
我需要确定有多少连续字段为空,具体取决于当天(“起始字段”)。
例如:
如果开始是 $ shippingtimearr [5] code>,它应该返回
3 code>,因为下一个“星期一”(
$ shippingtimearr [0] code>)是
NULL code>。
如果start是一个不是 NULL code>的数组值,它应该返回
0 code >; p>
for($ i = 2; $ shippingtimearr [$ i ] = 0; $ i ++){
$ counter ++;
}
code> pre>
NULL code>”。 p>
div>
Since nobody seemed to understand exactly what I was looking for, I will post a solution I came up with myself using a "while" loop:
$counter = 0;
$shippingtimearr = ["", "1630", "1530", "1530", "1530", "", ""];
$start = 3;
while ($shippingtimearr[$start++] == NULL) {
++$counter;
if ($start > 6) $start = 0;
}
$shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");
$contains_empty = count($shippingtimearr) - count(array_filter($shippingtimearr));
May be you are looking for some simpler answer like
<?php
$shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");
$counter = 0;
for($i=0;$i<count($shippingtimearr);$i++){
if($shippingtimearr[$i]=="")
$counter++;
}
echo $counter;
?>
You can use array_count_values(), check the live demo
<?php
$shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");
print_r(array_count_values($shippingtimearr)['']);