Daniel Tovesson
Daniel Tovesson

Reputation: 2600

Run the current index again in a foreach-loop

Is it possible to run the current index again when a certain condition is met in a foreach-loop? Posting a example below.

$array = array('this', 'is', 'my', 'array');
$bool = false;
foreach($array as $value){
    echo $value.' ';
    if($value == 'my' && !$bool){
        // Rerun the 'my' index again
        $bool = true;
    }
}

Desired output: this is my my array

Upvotes: 1

Views: 2794

Answers (2)

Alex Shesterov
Alex Shesterov

Reputation: 27565

Even though it may be possible (via prev or some other hack), the code written this way is hard to understand (even for yourself in a couple of years). For a programmer, the foreach construct (at the first glance) looks like a simple iteration over all elements of an array, without jumping back and forth.

Note also that prev inside a foreach loop may work in one PHP version but fail in other version! PHP docs say:

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

I would suggest using a while loop in you case (using either indexes or each-prev-next functions). The while construct is immediate signal for a programmer that the iteration logic is more complex than just sequential iteration over array elements.

$array = array('this', 'is', 'my', 'array');
$bool = false;

while (list($key, $value) = each($array))  
{
  echo $value.' ';
  if($value == 'my' && !$bool)
  {
    // Rerun the 'my' index again
    $bool = true;
    prev($array);
  }
}

Upvotes: 4

Carsten
Carsten

Reputation: 18446

Another variant:

<?php
$array = array('this', 'is', 'my', 'array');
$bool = false;

foreach ($array as $value) {
    do {
        echo $value.' ';

        if($value == 'my' && !$bool){
            // Rerun the 'my' index again
            $bool = true;
        } else {
            $bool = false;
        }
    } while ($bool);
}

Output (also see here):

this is my my array

Upvotes: 2

Related Questions