简体   繁体   中英

how to reset count in foreach loop in php?

looking at my example, what i am trying to do is to make sure that there is no null result

basically, foreach $array, if $xxx[$key] is null, restart the assignment from the start

below, i am hardcoding $k, $v and $y, but i don't know how big $array is so i cant just loop like this forever.

any ideas how to simplify this? It would be great if the foreach is on $array and not use for loops

$xxx = ['a','b'];
$array = [1,2,3,4,5,6,7,8,9];
$k = 0;
$v = 0;
$y = 0;
foreach($array as $key =>  $val){
    if(isset($xxx[$key])){
        var_dump($xxx[$key]);
    } else {
        if(isset($xxx[$k])){
            var_dump($xxx[$k]);
        } else {
            if(isset($xxx[$v])){
                var_dump($xxx[$v]);
            } else {
                var_dump($xxx[$y]);
                $y++;
            }
            $v++;
        }
        $k++;
    }
}

result:

string 'a' (length=1)
string 'b' (length=1)
string 'a' (length=1)
string 'b' (length=1)
string 'a' (length=1)
string 'b' (length=1)
string 'a' (length=1)
string 'b' (length=1)
null

Use the mod operator instead, that way it goes on indefinitely no matter the size of $array or $xxx.

$xxx = ['a','b','c','d'];
$array = [1,2,3,4,5,6,7,8,9];

foreach ($array as $key => $value) {
    var_dump($xxx[$key % count($xxx)]);
}

print out:

string(1) "a" 
string(1) "b" 
string(1) "c" 
string(1) "d" 
string(1) "a" 
string(1) "b" 
string(1) "c" 
string(1) "d" 
string(1) "a"

roll up your own function to check whether an item value is null or not then pass or set its value pass it as a callback function to array_map() or array_walk() to check out the values, so you get the callback:

array_walk($data, function(&$item, $key) {

  if ( $item === null ) {
    $item = something;
    // or do something else
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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