Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display all array elements in one column of table

I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
    <tr>
    <td>Array 1 first value</td>
        <td>Array 2 first value</td>
        <td>Array 3 first value</td>
    </tr>
    <tr>
     <td>Array 1 second value</td>
        <td>Array 2 second value</td>
        <td>Array 3 second value</td>
    </tr>
    <tr>
    <td>Array 1 third value</td>
        <td>Array 2 third value</td>
        <td>Array 3 third value</td>
    </tr>
</table>

This is how my arrays look like.

 $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);

This is how I tried to display but it did not work as expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foreach($array as $key => $arr){
echo '<tr>';

?>
        <td><?php 
        echo $arr[$key]->post_title;
        ?></td>
        <td><?php 
        echo $arr[$key]->post_title;
        ?> </td>
        <td><?php 
        echo $arr[$key]->post_title;
        ?> </td>
    <?php

echo '</tr>';
}

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

>Solution :

You can try like this

<?php 

$array1 = ['elm11','elm12','elm12'];

$array2 = ['elm21','elm22','elm23'];

$array3 = ['elm31','elm32','elm33'];

?>
<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
    <tr>
        <?php 
            foreach($array1 as $i => $elm){
        ?>
            <td><?php echo $elm ?></td>
            <td><?php echo (isset($array2[$i]) && !empty($array2[$i]) ) ? $array2[$i] : '' ?></td>
            <td><?php echo (isset($array3[$i]) && !empty($array3[$i]) ) ? $array3[$i] : '' ?></td>
        <?php 
            }
        ?>
    </tr>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading