I've used quite a lot of foreach loops to achieve this type of HTML table that has titles in the first cell of each row: <table>     <thead>        <tr>         <th></th><th><img src='img.jpg'>Product 1</th><th><img src='img.jpg'>Product 2</th>        </tr>     </thead>     <tbody>        <tr>          <td>Width</td><td>50mm</td><td>90mm</td>          <td>Material</td>Plastic<td></td><td>Gold</td>          <td>Diameter</td>60 mm<td></td><td>70mm</td>          <td>Battery Hours</td>60 hours<td></td><td>50 hours</td>        </tr>     </tbody>   </table>Is it necessary to use so many foreach loops? Do you have any other better way of getting this output?  $sql = SELECT * FROM product WHERE name IN ('Product 1','Product 2') ;  if ($wpdb->query($sql))  {    $rows = $wpdb->last_result;    $similar_com = ;    $similar_com .= <table><thead><tr><th></th>;    foreach($rows as $row)    {        $similar_com .= <img style='width:100px;height:100px' src='.$row->image_url.' alt='.$row->model_no.'>;    }    $similar_com .= </thead><tbody><tr><td>Width</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->width mm</td>;    }    $similar_com .= </tr><td>Material</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->material</td>;    }    $similar_com .= </tr><td>Case diameter</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->case_diameter (.plus($product->case_diameter - $row->case_diameter). mm)</td>;    }    $similar_com .= </tr><td>Case thickness</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->case_thickness (.plus($product->case_thickness - $row->case_thickness). mm)</td>;    }    $similar_com .= </tr><td>Case Material</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->case_material</td>;    }    $similar_com .= </tr><td>Battery Hours</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->battery_hours hours</td>;    }    $similar_com .= </tr><td>Special Functions</td>;    foreach($rows as $row)    {        $similar_com .= <td>$row->special_functions</td>;    }    $similar_com .= </tr></tbody></table>;   }
Foreach loop to generate HTML table with title in first cell of each row in PHP
php;html