Fadli Saad
Fadli Saad

Reputation: 222

Populate checkbox from array

Hi I've data for year store as serialize like this

a:2:{i:0;s:4:"2011";i:1;s:4:"2013";}
and have a list of predefined year like this:
$current_year = date('Y');
for($year = 2011; $year < $current_year; $year++)
{
$year;
}

So, I want to populate a list of checkboxes like below:
[x] 2011
[ ] 2012
[x] 2013
...

If the year is not in the predefined year (in this case 2011,2012 and 2013), the year should be unchecked.

I've search but so far the nearest solution is not in PHP

Upvotes: 0

Views: 1266

Answers (2)

Ananth
Ananth

Reputation: 1550

I have found the solution. Check this.

<?php 
 $dat='a:2:{i:0;s:4:"2011";i:1;s:4:"2013";}';
 $data=unserialize($dat); 
 $current_year = date('Y');
for($year = 2011; $year <= $current_year; $year++) 
{
    if(in_array($year,$data))   {       $checked="CHECKED";     }   else { $checked=""; } ?>
    <input type="checkbox" value="<?php echo $year; ?>" name="year[]"  <?php echo $checked; ?> > <?php echo $year; ?> <br/>
<?php } ?>

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

$years = unserialize($mysql_years);
$current_year = date('Y');
for ($year = 2011; $year < $current_year; $year++) {
    $checked = '';
    if (in_array($year, $years)) {
        $checked = ' checked';
    }
    echo "<input type=checkbox value=$year$checked>";
}

Upvotes: 3

Related Questions