Using Variables for the index in a for loop

The goal of this code was to create a table from an associative array. I need to create horizontal rows where the keys need to be used as “headers” while the values are posted below each header. I need to be able to reuse the code with associative arrays of unknown lengths and varying number of columns allowed in the tables. I realize this is not set up as a function. I’m just playing with the code for now.
The code that I have actually does work. I’m not sure if it’s “proper” form especially here - $startIndex = $index in the for loop.
I create two rows at a time - one for the header, one for the values. After the end of these two rows, I’m re-setting the index on the for loop so it runs through the next group in the array. I’m trying to get better at coding and would like some input on what I’ve done.
[php]

Horizontal <?php $array = array( "A" => 1, "B" => 2, "C" => 3, "D" => 4, "E" => 5, "F" => 6, "G" => 7, "H" => 8, "I" => 9, "J" => 10, "K" => 11, "L" => 12, "M" => 13 ); $maxColumns = 8;//set the number of columns allowed in the table - this varies by table $arrayOfKeys = array_keys($array);//grab the keys from the initial array $count = count($arrayOfKeys);//gets a count of the number of items in the array $maxRows = ceil($count/$maxColumns) * 2;//takes the count and determines the number of rows based on the number of items and the maxColumns * 2 for total rows (need a "header" and value for each set of keys/values in the array $endIndex = $maxColumns-1;//initialize the endIndex on the loop that runs the $startIndex = 0;//initialize the start index for the second loop which will loop through the array assigning keys to first row - value to second for ($row=1; $row<=$maxRows; $row++){//loops based on the number of rows required to generate the table for the number of cells required echo '';//start the row $rowEvenOdd = ($row % 2); //figures whether an even or odd row for ($index=$startIndex; $index<=$endIndex; $index++){//creates the rows if($rowEvenOdd == 1) {//if the row is odd, grab and display the key if(array_key_exists($index, $arrayOfKeys)) {$thiskey = $arrayOfKeys[$index];} else {$thiskey =" ";} echo ""; }//end of odd rows if($rowEvenOdd == 0) {//if the row is even, grab and display the value if(array_key_exists($index, $arrayOfKeys)) {$thisvalue = $array[$arrayOfKeys[$index]];} else {$thisvalue =" ";} echo ""; }//end of odd rows }//end of loop to generate content for the cells echo '';//end the row if($rowEvenOdd == 0) {$startIndex = $index; $endIndex = $index + $maxColumns-1;/* reset the index begin and end to loop through next group of rows */ } }//end loops that creates the rows ?>
$thiskey". $thisvalue ."
[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service