如何在第x个元素后停止递减迭代?

时间:2015-06-18 03:25:13

标签: php for-loop iteration

所以我有一个正在减少的for循环......

<head>

<link rel="stylesheet" href="css/common.css" />
<script src="js/common.js"></script>

Desktop only css and js
<link rel="stylesheet" href="css/desktop.css" />
<script src="js/desktop.js"></script>
</head>

几乎总结了我的问题。我如何制定结束迭代 - 让我们说在打印5个元素之后我想停止迭代。

3 个答案:

答案 0 :(得分:1)

$j = 0;
for ($i=count($array); $i>0; $i--)
{
    if(condition)
    {
        DO SOMETHING like print the element in a decreasing manner;
        $j++;
    }
    if($j > 4){
        break;
    }
}

答案 1 :(得分:0)

尝试反转循环计数。尝试增加,而不是减少,因此您将计算正在打印的项目数。

<?php
for ($i = 0; $i < count($array); $i++)
{
    if(condition)
    {
        /* DO SOMETHING like print the element in a decreasing manner */
    }

    /* replace (nth) with the needed number */
    if($i === (nth)) break;
}

答案 2 :(得分:0)

您可以根据计数设置限制,例如:

$loop_limit = 5;
$array_count = count($array);
$last = $array_count - $loop_limit;

for ($i = $array_count; $i >= $last ; --$i) {
    if ( $i == $last ) {
            //Do whatever you need at this point
    }
    //do the normal loop action
}