Jump to content

Using arithmetic operators to define a for loop...


bukwus

Recommended Posts

Hello

I'm trying to use PHP "for loops" to build a table of 10 rows with 5 columns and I'm sure there's a better way to do this, but the result is the page won't fully load and continually spins its wheel. Here's the code:

 

$states = array(1 => 'AK','AL','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','OZ','PA','PR','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI'
);

<table id="stateCheck">
            <?php
            	for ($i = 1; $i <= 10; $i++) {
                	echo '<tr>';
                    for ($j = 5*$i; $j <= $j+4; $j++) {
                    	echo '<td>
                              <input type="checkbox" name="state" value="'.$states[$j].'" /> '.$states[$j].'
                          </td>';
                    }
                    echo '</tr>';
                }
            ?>
            	<tr>
                	<td>
                    	<input type="checkbox" name="state" value="WV" /> WV
                    </td>
                    
                    <td>
                    	<input type="checkbox" name="state" value="WY" /> WY
                    </td>
                </tr>
            </table>

 

Is it breaking because I'm using arithmetic operators to define the nested for loop?

 

Many thanks

I'm not sure what you mean by breaking.  Does it timeout or just not work? Anyway, try this code:

<?php
$states = array(1 => 'AK','AL','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','OZ','PA','PR','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI'
);
$idx = $count = 0;
$list = '<table>';
foreach($states as $state)
{
if($count == 0)  $list .= "<tr>";

$list .= "<td align='center' width='20%'>{$state}</td>";	

++$idx; 
++$count; 

if ( ( $count == 5 ) OR ( $state == end( $states ) ) )
{
	$count = 0; 
}
}

$surplus = 5 - ($idx - (5 * (ceil($idx / 5) - 1)));
if($idx > 5)
{ 
for($i = 1; $i <= $surplus; $i++)
{ 
	$list .= '<td> </td>'; 
}
}
$list .= '</tr>';
echo $list;

 

Edit: Oops, I didn't include the html for your checkboxes, make sure you add that if you use this code.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.