smijith
smijith

Reputation: 13

Checkbox arrays looping issue

I have 5 checkboxs, my array has 3 elements if the array element same as checkbox value then that checkbox checked but it should print only one time

<?php
$selvals = array("Manhattan", "Bronx", "Brooklyn");
    $myArray = explode(',', $selvals);
    foreach($myArray as $i)
    {

    ?>

    <label class="checkbox-inline"><input type="checkbox" <?php if($i == "Manhattan"){ echo 'checked="checked"';}?> name="manhattan" value="Manhattan" >Manhattan</label>
    <label class="checkbox-inline"><input type="checkbox" <?php if($i == "Bronx"){ echo 'checked="checked"';}?> name="bronx" value="Bronx" >Bronx</label>
    <label class="checkbox-inline"><input type="checkbox" <?php if($i == "Brooklyn"){ echo 'checked="checked"';}?> name="brooklyn" value="Brooklyn" >Brooklyn</label>
    <label class="checkbox-inline"><input type="checkbox" <?php if($i == "Queens"){ echo 'checked="checked"';}?> name="queen" value="Queens" >Queens</label>
    <label class="checkbox-inline"><input type="checkbox" <?php if($i == "Staten Island"){ echo 'checked="checked"';}?> name="staten" value="Staten Island" >Staten Island</label>

    <?php
    }
    ?>

Upvotes: 0

Views: 22

Answers (2)

Pradyut Manna
Pradyut Manna

Reputation: 588

I think your code should be like this:- :)

<?php
$selvals = array("Manhattan", "Bronx", "Brooklyn");
?>
<label class="checkbox-inline"><input type="checkbox" <?php if(in_array("Manhattan",$selvals)){ echo 'checked="checked"';}?> name="manhattan" value="Manhattan" >Manhattan</label>
<label class="checkbox-inline"><input type="checkbox" <?php if(in_array("Bronx",$selvals)){ echo 'checked="checked"';}?> name="bronx" value="Bronx" >Bronx</label>
<label class="checkbox-inline"><input type="checkbox" <?php if(in_array("Brooklyn",$selvals)){ echo 'checked="checked"';}?> name="brooklyn" value="Brooklyn" >Brooklyn</label>
<label class="checkbox-inline"><input type="checkbox" <?php if(in_array("Queens",$selvals)){ echo 'checked="checked"';}?> name="queen" value="Queens" >Queens</label>
<label class="checkbox-inline"><input type="checkbox" <?php if(in_array("Staten Island",$selvals)){ echo 'checked="checked"';}?> name="staten" value="Staten Island" >Staten Island</label>

Upvotes: 1

Rax Weber
Rax Weber

Reputation: 3780

The second parameter of your explode function should be a string. But you don't need it, just remove the explode statement and replace the $myArray with $selvals in the loop.

$selvals = array("Manhattan", "Bronx", "Brooklyn");
foreach ($selvals as $i)
         ^^^^^^^

Upvotes: 0

Related Questions