sadefer sadefer - 1 month ago 9
PHP Question

Creating a table with three arrays

I have three arrays, for example:

$one = array(1, 3, 7, 8, 9);
$two = array('a', 'd', 'b', 'e', 'r');
$three = array('$', '!', '^', '@', '*');


I would like to do:

<table>
<tr><th>1</th><td>a</td><td>$</td></tr>
<tr><th>3</th><td>d</td><td>!</td></tr>
<tr><th>7</th><td>b</td><td>^</td></tr>
<tr><th>8</th><td>e</td><td>@</td></tr>
<tr><th>9</th><td>r</td><td>*</td></tr>
</table>


Is this possible?

Answer

This should work, however it does make the assumption that all of these arrays will have the same number of elements.

First off , we loop through all the keys , then loop through all the arrays and apply the index key to output.

<?php
$one = array(1, 3, 7, 8, 9);
$two = array('a', 'd', 'b', 'e', 'r');
$three = array('$', '!', '^', '@', '*');
?>
<table>
<?php
foreach (array_keys($one) as $val) {
?>
<tr>
<?php 
    foreach(array($one, $two, $three) as $cur){
?>
        <td><?php echo isset($cur[$val]) ? $cur[$val] : null ?></td>
<?php
    }
?>
</tr>
<?php
}
?>
</table>
Comments