Rowan Helmich
Rowan Helmich

Reputation: 21

PHP two while loops taking turns

I want to make an output with two while loops in PHP where both while loops take turns by returning values like if they are 'taking turns'...

For example: While loop1 echoes A1, A2, A3 etc While loop2 echoes B1, B2, B3 etc

I want my output to be like this:

A1
B1
A2
B2
A3
B3
etc etc

Anyone has any ideas on how to do this? I want to implement this idea in a bar-graph kind of overview. I want to compare every week of two years' data. The bar graph is done with using a While Loop. It's a horizontal bar graph (the bars 'lay down') and I want to make it like this:

Week 1 of year x
Week 1 of year x-1
Week 2 of year x
Week 2 of year x-1
Week 3 of year x
Week 3 of year x-1

etc

Thanks in advance!

Upvotes: 0

Views: 190

Answers (1)

Mark Baker
Mark Baker

Reputation: 212442

If the values come from two different arrays, you can iterate through them together using a MultipleIterator

$firstArray = array('A1','A2','A3');
$secondArray = array('B1','B2','B3');

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($firstArray));
$mi->attachIterator(new ArrayIterator($secondArray));

foreach ( $mi as $value ) {
    list($first, $second) = $value;
    echo $first , PHP_EOL , $second , PHP_EOL;
}

Upvotes: 5

Related Questions