snookian
snookian

Reputation: 873

For loop display radio buttons with first one checked

I have a for loop that displays radio buttons and I want the first one to display as checked. But when I put a if statement inside the for loop for this the page nevers loads. Any ideas?

$mains = array(0=>'Beef Steak', 1=>'Chicken Breast', 2=>'Pork Chops');
$mainscount = count($mains);

<?php for ($mainNO = 0; $mainNO < $mainscount; $mainNO++) { ?>
  <label for="mains<?php echo $mainNO ?>" class="radiobutton"><?php echo $mains[$mainNO]; ?></label>
  <input type="radio" name="mains" id="mains<?php echo $mainNO; ?>" value="<?php echo $mainNO; ?>" 
  <?php if($mainNO = 0){ echo 'checked="checked"'; } ?>/>
<?php } ?>

Upvotes: 0

Views: 832

Answers (3)

Pawan Thakur
Pawan Thakur

Reputation: 591

// Note: You used single = in if condition that is wrong, it will create indefinite loop . Tested code.

    $mains = array(0=>'Beef Steak', 1=>'Chicken Breast', 2=>'Pork Chops');
    $mainscount = count($mains);

     for ($mainNO = 0; $mainNO < $mainscount; $mainNO++) { 

        // Checked if value is 0
        if($mainNO == 0){  $checked = 'checked="checked"'; }else { $checked =''; };

        echo "<label for='mains".$mainNO."' class='radiobutton'>".$mains[$mainNO]."</label>";
        echo "<input type='radio' name='mains' id='mains".$mainNO."' value='".$mainNO."' $checked   />";


    } 

Upvotes: 0

sanil gurung
sanil gurung

Reputation: 41

u are using assingment operator in comparision statement

<?php for ($mainNO = 0; $mainNO < $mainscount; $mainNO++) { ?>
<label for="mains<?php echo $mainNO ?>" class="radiobutton"><?php echo $mains[$mainNO]; ?></label>
<input type="radio" name="mains" id="mains<?php echo $mainNO; ?>" value="<?php echo $mainNO; ?>"
    <?php if ($mainNO == 0) {
        echo " checked";
    } ?>/>

and in HTML5 you can use checked only

<input type="checkbox" checked>

Upvotes: 0

Exprator
Exprator

Reputation: 27503

<?php for ($mainNO = 0; $mainNO < $mainscount; $mainNO++) { ?>
    <label for="mains<?php echo $mainNO ?>" class="radiobutton"><?php echo $mains[$mainNO]; ?></label>
    <input type="radio" name="mains" id="mains<?php echo $mainNO; ?>" value="<?php echo $mainNO; ?>"
        <?php if ($mainNO == 0) {
            echo ' checked="checked" ';
        } ?>/>
<?php } ?>

you use = where you should use ==

Upvotes: 1

Related Questions