Patrioticcow
Patrioticcow

Reputation: 27048

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

Upvotes: 1

Views: 1958

Answers (2)

Paul Carlton
Paul Carlton

Reputation: 2993

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"

Upvotes: 2

Adriano Rosa
Adriano Rosa

Reputation: 8761

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
  }
});

Upvotes: 0

Related Questions