Search code examples
phparraysfor-loopdynamic-arrays

How do I echo this array in a for loop?


I have some arrays that have each 4 values in them, named:

$myarray_row0
$myarray_row1
$myarray_row2

So normally I can use this echo statement to get at the values in the first array:

echo 'My value is '.$myarray_row0[0];   // This works fine

But I want to use a FOR LOOP to iterate through them and I'm getting stuck because I want to use something like:

for ($i=0; $i<=10; $i++)
{
 echo 'My value is '.$myarray_row[$i][[$i]];
 echo 'My value is '.$myarray_row[$i][$i+1]];
 echo 'My value is '.$myarray_row[$i][[$i+2]];
 echo 'My value is '.$myarray_row[$i][[$i+3]];
}

I'm not using the correct syntax for the $i's and the brackets needed... I'm TRYING (but failing) to get the echo to spit out the arrays contents, such as:

$myarray_row0[0]
$myarray_row0[1]
$myarray_row0[2]
$myarray_row0[3]
etc

Note that it's not truly a multidimensional array, it's one dimensional, but it almost LOOKS like it is multi-dimensional since the array names have 'row0', 'row1', 'row2', etc in them.

Anyone know the syntax for getting a variable like $myarray_row0[1] to be echo'ed using the $i's that are available inside the for loop?

THANKS!


Solution

  • You'd need to use a variable variable name. (its been a while since ive used php so might be wrong)

    for ($i=0;$i<10l$i++) {
        echo 'My variable name is '.${'myarray_row'.$id}[$i+0];
        echo 'My variable name is '.${'myarray_row'.$id}[$i+1];
        echo 'My variable name is '.${'myarray_row'.$id}[$i+2];
        echo 'My variable name is '.${'myarray_row'.$id}[$i+3];
    }
    

    However, its generally a good idea to not use them at all. making a multi-dimensional array instead would be much better for your case.

    Question: if your $myarray_rowN has 4 elements why does your example have $i+X in the index?

    surely it will go out of bounds after the first iteration :/ (1+1 OK, 1+2 OK, 1+3 OK 1+4 !OK etc)

    possibly something like this might be better? (could be javascript though)

    $index = 0;
    $rows = array();
    while (isset(${'myarray_row'.$i})) {
        array_push($rows, ${'myarray_row'.$i});
    }
    foreach ($rows as $row) {
        echo 'My variable name is '.$row[0]."\r\n";
        echo 'My variable name is '.$row[1]."\r\n";
        echo 'My variable name is '.$row[2]."\r\n";
        echo 'My variable name is '.$row[3]."\r\n";
    }