Jump to content

Default checked radio button within foreach loop ?


PWaddict
 Share

Recommended Posts


$i = 0;//set counter

$out ='';

$checked = '';

foreach($foo as $bar) {

if($i == 0) $checked = "checked"

//radio button stuff here...+ stuff with $bar...

$out .= "<input type='radio' name='my_radio' value='{$bar}' {$checked}>";

$i++;

}

echo $out;

Edited by kongondo
typos
  • Like 1
Link to comment
Share on other sites

We really need to see some code, but the general principle is to set up a counter and and if it equals 0 (the first loop), then add the "checked", eg:

$items = $pages->get(1)->children();

$i=0;
foreach($items as $item) {
    echo '<input type="radio" name="items" value="'.$item->name.'" ' . ($i==0 ? "checked" : "") . ' /> ' . $item->title;
    $i++;
}

Note the ternary operator checking to see if $i == 0 before outputting checked.

EDIT: Well and truly beaten by Kongondo :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...