0

I'm trying to loop in a table row 16 times with 2 elements of array. I know I can't loop 16 times with 2 elements of data but I want to display a table which has 16 row and only first 2 row will have data and others will leave blank. Same as the image below

img here

I have tried this code but its not what I want

<th>No</th>
<th>Id</th>
<th>Name</th> 
for($i=1; $i<=16; $i++)
{
<tr>
<td> echo $i </td>
foreach($array as $a){
<td> $a->id </td>
<td> $a->name </td>
}
</tr>
}


4
  • 1
    So, output array data and then iterate 14 times. Commented May 24, 2019 at 20:07
  • no, not like that. :( Commented May 24, 2019 at 20:09
  • "I have tried this code but its not what I want" - I can see why. That would just output the PHP-code as text since you're not having them in any PHP-blocks. Commented May 24, 2019 at 20:09
  • And like what then? Commented May 24, 2019 at 20:10

1 Answer 1

1

You're looping through your entire array, 16 times. I assume that your array only has 2 elements in it. I'm going to assume it may not always have 2 elements in it, and if it has, say, 8 elements in it, you want the first 8 rows populated with data, but you always want 16 rows to display?

Additionally, I'm assuming that your $array variable is numerically indexed.

If all of that is true, then what you want is to eliminate your foreach, and just access the array element by index:

<thead>
    <tr>
        <th>No</th>
        <th>Id</th>
        <th>Name</th>
    </tr>
</thead>
<tbody>
<?php for ($i=0; $i<=15; $i++) {
    if (!empty($array[$i])) { ?>
    <tr>
        <td><?= $i+1; ?></td>
        <td><?= $array[$i]->id; ?></td>
        <td><?= $array[$i]->name; ?></td>
    </tr>
    <?php }
    else { ?>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <?php } ?>
<?php } ?>
</tbody>

Note that PHP arrays are zero-based, hence why I did 0-15 instead of 1-16.

Sign up to request clarification or add additional context in comments.

4 Comments

Great! If your problem is solved, consider accepting this as correct, so that future visitors will know you're not still looking for answer.
Yes i did brother
The solution is solid but as a note, you should make an effort to use the alternative control structure for readability: php.net/manual/en/control-structures.alternative-syntax.php - Slightly off topic, but worth knowing :)
Decisions like that will likely be driven by the style conventions adhered to by the company or group you're working with. For one, I don't find the alternative syntax more readable and I've never seen it recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.