Sagunthala K
Sagunthala K

Reputation: 27

how to make checked checkbox in two arrays

Here i have two arrays 1.response 2.selected_amenties,in first array value i displayed in checkbox, now i want to make checked values for Swimming Pool and Power Backup because of this values equal to the first array (response ), how can do this ?

<?php
 $response = Array
(
     Array
        (
            "id" => "57e2340eaebce1023152759b",
            "name" => "Squash Court",
            "amenityType" => "Sports"
        ),
    Array
        (
            "id" => "57e23470aebce1023152759d",
            "name" => "Swimming Pool",
            "amenityType" => "Sports"
        ),
     Array
        (
            "id" => "57e2347caebce1023152759e",
            "name" => "Power Backup",
            "amenityType" => "Convenience"
        ),
     Array
        (
            "id" => "57e23486aebce1023152759f",
            "name" => "Day Care Center",
            "amenityType" => "Convenience"
        )
);  

$selected_amenties = Array( "0" => "Swimming Pool",
                            "1" =>  "Power Backup"
                          );
foreach($response as $amenity)
{
?>
<div class="checkbox">
<input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>
</div>
<?php
}
?>

Upvotes: 1

Views: 45

Answers (2)

harry
harry

Reputation: 483

$selected_amenties = array('Swimming Pool', 'Power Backup');

foreach($response as $amenity) {
    $check = '';
    in_array($amenity, $selected_amenties) and $check = ' checked="checked" ';
    echo '<div class="checkbox">';
    echo '<input type="checkbox" ' . $check . ' class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>';
    echo '</div>';
}

Upvotes: 0

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

Try like this:

<?php 
foreach($response as $amenity)
{ 
    $checked = in_array($amenity['name'], $selected_amenties) ? 'checked' : '';

    ?>
    <div class="checkbox">
    <input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name'] ?>" <?php echo $checked; ?>><?php echo $amenity['name']?>
    </div>
<?php
}
?>

Upvotes: 1

Related Questions