skip to Main Content

I want to make static data row in table for 10 rows. I have 3 data foreach (item01, item02, item03) like this.

<table>
<?php foreach($data as $row): ?>
<tr>
<td><?php echo $row->item_no; ?></td>
</tr>
<?php endforeach;
</table>

I want to make in my table like this :

No Item No
1 Item01
2 Item02
3 Item03
4
5
6
7
8
9
10

How I can do that in my php code ?

4

Answers


  1. first get the size of your data:

    $items=count($data);
    

    then you could simply use a for loop:

    for($i=0; $i<10; $i++){  
        if($i<$items){
            $line=$data[$i]->item_no;
        }else{
            $line="nothing here in line:" . $i+1;
        }
        echo "<br>$line";
    }
    

    which outputs:

    item01
    item02
    item03
    nothing here in line:4
    nothing here in line:5
    nothing here in line:6
    nothing here in line:7
    nothing here in line:8
    nothing here in line:9
    nothing here in line:10
    
    Login or Signup to reply.
  2. Use forloop to loop 10 row for the table.

    for($i = 0; $i < 10; $i++){
        <tr>
            <td><?= $i + 1 ?></td>
            <td><?= ($data[$i]) ? $data[$i]->item_no : '' ?></td>
        </tr>
    }
    

    This code meaning if $data is not empty then show $data->item_no else show empty.

    <?= ($data[$i]) ? $data[$i]->item_no : '' ?>
    
    Login or Signup to reply.
  3. Try this

    <table>
    <?php while(@$count<10){ ?>
      <tr>
        <td><?=@$count+=1;?></td>
        <td>item<?=sprintf("%02d", @$count);?></td>
      </tr>
    <?php }?>
    </table>
    Login or Signup to reply.
  4. Try This:

    $items = ['items 01', 'items 02', 'items 03', 'items 04'];
    $output = '';
    if( !empty($items) ){
      $i = 1;
      $output .= '<table>';
      foreach( $items as $item ){
              $output .= '<tr>';
              $output .= '<td>'.$i.'</td>';
              $output .= '<td>'.$item.'</td>';
              $output .= '</tr>';
              
              $i++;
      }
      $output .= '</table>';
    }
    echo $output;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search