is there a way in PHP to restart a loop in a foreach, or change the test value in a switch?

若如初见. 提交于 2019-12-22 10:05:31

问题


if i'm looping over an array, and while in the middle of one of the loops i discover some small issue, change ...something..., and need to try again ... is there a way to jump back to the top of the loop without grabbing the next value out of the array?

i doubt this exists, but it would be some keyword like continue or break. in fact, it would be a lot like continue, except that it doesn't get the next item, it maintains what it has in memory.

if nothing exists, can i insert something into the array in such a way that it will become the next key/value in the loop?

maybe this would be easier with a while(array_shift())...

or i suppose a recursive function inside the loop might work.

well, my question is evolving as i type this, so please review this pseudo code:

foreach($storage_locations as $storage_location) {
    switch($storage_location){
        case 'cookie':
            if(headers_sent()) {
                // cannot store in cookie, failover to session
                // what can i do here to run the code in the next case?
                // append 'session' to $storage_locations?
                // that would make it run, but other items in the array would run first... how can i get it next?
            } else {
                set_cookie();
                return;
            }
        break;

        case 'session':
            set_session();
            return;
        break;
    }
}

i'm sure there is no keyword to change the value tested against in the switch mid-stream... so how should i refactor this code to get my failover?


回答1:


Not with a foreach, but with more manual array iteration:

while (list($key, $value) = each($array)) {
    if (...) {
        reset($array); // start again
    }
}

http://php.net/each
http://php.net/reset

It seems like a simple fall through would do the trick though:

switch ($storage_location) {
    case 'cookie':
        if (!headers_sent()) {
            set_cookie();
            break;
        }

        // falls through to next case

    case 'session':


来源:https://stackoverflow.com/questions/13382183/is-there-a-way-in-php-to-restart-a-loop-in-a-foreach-or-change-the-test-value-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!