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

changokun picture changokun · Nov 14, 2012 · Viewed 12.2k times · Source

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?

Answer

deceze picture deceze · Nov 14, 2012

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':