简体   繁体   English

PHP:foreach-反向1迭代

[英]PHP: foreach - reverse 1 iteration

Let's say I've a code: 假设我有一个代码:

foreach($array as $key => $value)
{
    //do something
    if($var === true) //"reverse"
}

is it possible to "reverse" foreach, so it'll "run" with the same array's element it was "running" when called to "get back" ;)? 是否有可能“反向” foreach,因此它将在调用“取回”时与“正在运行”的同一数组元素“运行”;)?

You will have to use a normal for loop and make the last parameter (the modifying part) depend on a variable. 您将必须使用普通的for循环,并使最后一个参数(修改部分)取决于变量。

Expr3 in the following manual entry: http://php.net/manual/en/control-structures.for.php 在以下手动输入项中的Expr3: http ://php.net/manual/zh/control-structures.for.php

Not with a foreach , no. 不带foreach ,不。 You could do this: 您可以这样做:

$array = range(1,10);

for (
    $dir = 1, reset($array); 
    $val = current($array); // for keys, use list($key,$val) = each($array)
    $dir == 1 ? next($array) : prev($array)
) {
    echo "{$val}\n";
    if ($val == 7) {
        $dir = -1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM