Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中增加循环内的迭代次数?_Php_Loops_Iteration - Fatal编程技术网

如何在php中增加循环内的迭代次数?

如何在php中增加循环内的迭代次数?,php,loops,iteration,Php,Loops,Iteration,我正在使用自定义分页系统,遇到以下问题。当从集合中筛选出一个元素时,最终数组的大小将小于所需的大小。因此,我正在寻找一种解决方案,以增加循环中的迭代次数,从而始终获得由50个元素组成的数组 $limit = 50; //Number of elements I want to fetch for($x=0; $x<$limit; $x++){ if ($elementIsNotFiltered) { //add element to $someArray;

我正在使用自定义分页系统,遇到以下问题。当从集合中筛选出一个元素时,最终数组的大小将小于所需的大小。因此,我正在寻找一种解决方案,以增加循环中的迭代次数,从而始终获得由50个元素组成的数组

$limit = 50; //Number of elements I want to fetch

for($x=0; $x<$limit; $x++){

    if ($elementIsNotFiltered) {
        //add element to $someArray;
    }
    else {
        //increase the number of iterations, so even if some elements are filtered out,
        //the size of $someArray will always be 50 
    }

}
$limit=50//要获取的元素数
对于($x=0;$x)
试过了吗

你也可以反过来做同样的事情:

else {
    --$x;
}
或者更有效一点:

$x = 0;
while ($x != 50) {
    if ($notFiltered) {
        ++$x;
    }
}
如果还要保存计数器变量,可以使用:

while (!isset($array[49])) {
}
!isset($array[49])
这里只是
count($array)<50
的同义词,而是在
while()循环中执行,当您最终达到
$limit
时,请使用while循环


while(count($somearray)<50&&/*元素仍然*/)…

我觉得你在寻找
while
循环-而不是
for
循环:

while ($items < 50 && [more items to filter]) {
    if ([add to array]) {
       $items++;
    }
}
while($items<50&&[more items to filter]){
如果([添加到数组]){
$items++;
}
}

如果您真的想在
for
循环中执行此操作,您可以随时修改
$x
,但这会使您的代码无法阅读且难以维护-我建议不要执行此操作…

是的;此操作。for循环用于您知道数字时,而循环用于您不知道数字但您知道何时得到数字时但是,为什么要使用无限while循环,然后使用break而不是使用while指定条件呢?您可以轻松地在循环中设置条件,而不是使用break$x=true;while($x){if(){$x=false;}}@ecu-不如改为
$x--
?@nikic,不起作用的原因是循环完成后else子句将触发-此时更改$limit为时已晚。你能解释一下为什么会这样吗,Craig?至少我不明白为什么不应该执行它:(
while ($items < 50 && [more items to filter]) {
    if ([add to array]) {
       $items++;
    }
}