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.
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>