imgrooot Posted December 13, 2015 Share Posted December 13, 2015 Say I have this loop. foreach($record as $row) { <div class="hello">Hello World!</div> } I want to loop through and add a letter alongside the "Hello World!" above. To do that, I found this code. $azRange = range('A', 'Z'); foreach ($azRange as $letter) { print("$letter\n"); } How can I combine the two loops so that I get a result like this? A Hello World! B Hello World! C Hello World! D Hello World! E Hello World! F Hello World! Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted December 13, 2015 Share Posted December 13, 2015 I assume your “Hello World!” should actually be a dynamic string depending on $row? The easiest way to implement parallel iteration is to iterate one array with a foreach loop and the other with repeated each() calls: <?php $record = range(1, 26); // test data $letters = range('A', 'Z'); foreach ($record as $row) { $letterElement = each($letters); assert($letterElement !== false, 'Not enough letters for number of rows.'); $letter = $letterElement['value']; echo "$letter: $row<br>"; } For more complex scenarios, there are also iterator classes in the SPL extension. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.