Jump to content

Recommended Posts

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!

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.