2017-07-14 74 views
0

我有一個for循環,顯示單選按鈕,我想第一個顯示爲選中。但是,當我把一個if語句放在for循環中時,頁面neine加載。有任何想法嗎?For循環顯示單選按鈕與第一個選中

$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 } ?> 

回答

1
<?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 } ?> 

您使用=,你應該使用==

0

u的使用assingment運營商在比較聲明

<?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"; 
    } ?>/> 

,並在HTML5中,你可以使用檢查

<input type="checkbox" checked> 
0

//注意:您使用single = in if條件是錯誤的,它會創建無限循環。測試過的代碼。

$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 />"; 


    }