2

Is there a way when using foreach in PHP that I can test if part of the array equals a variable, do something, but then have foreach continue on the previous position of the array next loop through?

Simple version of my code:

<?php
$t=1;
foreach($getAllDetails as $allrecords)  {                   
    if ($allrecords[0] != $t){
    echo '<b>'.$t.'.---------------------------------</b><br>';
    }else{                      
?>
    <b>
    <?php 
    echo $allrecords[0].'. '. $allrecords[10].', '.$allrecords[2].', '.$allrecords[11].', '.$allrecords[12].', '.round($allrecords[6],1).'%, '.$allrecords[8].'oz, $'.round($allrecords[5]); 
    ?>
    </b>
    }
}

So my array would produce something like this

$allrecords[0]=2 & T=2
$allrecords[0]=3 & T=3
$allrecords[0]=4 & T=4
$allrecords[0]=5 & T=5
$allrecords[0]=6 & T=6
$allrecords[0]=7 & T=7
$allrecords[0]=8 & T=8
$allrecords[0]=9 & T=9
$allrecords[0]=11 & T=10 <----Here if ($allrecords[0] != $t) - do something
$allrecords[0]=12 & T=11 <----Here is where I need the foreach to step back and start at where the value of $allrecords[0] caused the if statement to fire so $allrecords[0] should be equal to the previous or in this example 11

3
  • Why don't you just use for ($i = 0; $i < count($getAllDetails); $i++)? Foreach is not for stepping back. Commented May 13, 2014 at 2:35
  • I think you are looking for a for loop using a numeric iterator to represent the key here, where you can modify the iterators value at any point to force it to step back a record. Commented May 13, 2014 at 2:36
  • No. foreach loops go from the first element to the last; there is no way to go backwards. Use a for, while or do-while loop instead. Commented May 13, 2014 at 3:09

1 Answer 1

3

Try using a for loop instead:

$t = 1;

for($i = 0, $numRecords = sizeof($getAllDetails), $i < $numRecords; ++$i) {
    if ($getAllDetails[$i][0] != $t) {
        echo '<b>'.$t.'.---------------------------------</b><br>';

        // you can change the value of $i here to step back (i.e. --$i)
    } else {                      
?>
    <b>
    <?php 
        echo $getAllDetails[$i][0].'. '. $getAllDetails[$i][10].', '.$getAllDetails[$i][2].', '.$getAllDetails[$i][11].', '.$getAllDetails[$i][12].', '.round($getAllDetails[$i][6],1).'%, '.$getAllDetails[$i][8].'oz, $'.round($getAllDetails[$i][5]); 
    ?>
    </b>
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.