Search code examples
phparraysloops

How to looping number of columns same as value of array in php


I want to make loop put value in the columns same as number value when number in array, but the problem is too many columns are empty.

My code is

$answer = [
    1 => "B",
    2 => "D",
    3 => "C",
    7 => "C",
    8 => "C",
    9 => "C",
    10 => "C"
];
for ($i=1; $i <= 25; $i++){
    foreach ($answers as $no => $value) {
        if ($no == $i) {
            echo "<td>" . $value . "</td>";
        } else {
            echo "<td></td>";
        }
    }
} 

my table


Solution

  • You only need one loop.

    If you are only interested in the present values in $answers, just use the inner loop.

    foreach ($answers as $no => $value) {
        echo "<td>".$value."</td>";
    }
    

    If you want to print out 25 <td>s including an empty ones when the values in $answers are not present, then you use the outer loop. However you can reference an index in $answers array by $answers[index], so $answers[1] will be "B", and so on. So for each index from 1 to 25, it can be referenced by $answers[$i].

    When the value is not present in a given index, for example at index 4, $answers[4] will give you an error. You can check for it and give a default value e.g. $answers[4] ?? '' will instead give an empty string and not throw an error.

    for ($i = 1; $i <= 25; $i++) {
        echo "<td>" .($answers[$i] ?? '') ."</td>";
    }