The example below also works with associative arrays + arrays with odd elements.
Code for associative AND indexed array:
$aFiles = ['test'=>"A","B",'c'=>"C","D","E","F",'g'=>"G","H",'iii'=>"I"]; $aKeys = array_keys($aFiles); $aRows = ceil(count($aFiles) / 2); echo '<table>'; for($i=0; $i < $aRows; $i++) { echo '<tr>' . ' <td>' . $aFiles[$aKeys[$i]] . '</td>' . ' <td>' . (isset($aKeys[$i+$aRows]) ? $aFiles[$aKeys[$i+$aRows]] : 'empty') . '</td>' . '</tr>'; } echo '</table>';
Code for an ONLY indexed array:
$aFiles = ["A","B","C","D","E","F","G","H","I"]; $aRows = ceil(count($aFiles) / 2); echo "<table>"; for($i=0; $i < $aRows; $i++) { echo "<tr>" . " <td>" . $aFiles[$i] . "</td>" . " <td>" . (isset($aFiles[$i+$aRows]) ? $aFiles[$i+$aRows] : "empty") . "</td>" . "</tr>"; } echo "</table>";
The output for both examples is identical:
<table> <tr> <td>A</td> <td>F</td> </tr> <tr> <td>B</td> <td>G</td> </tr> <tr> <td>C</td> <td>H</td> </tr> <tr> <td>D</td> <td>I</td> </tr> <tr> <td>E</td> <td>empty</td> </tr> </table>
source share