I'm coding an edit form and I can't get the part where you check previously checked checkboxes to function properly.
For example I have a list of five items in a database, I previously checked two of them and saved the form. When I press edit on the form, I need to get this again:
[ ] Item 1
[X] Item 2
[ ] Item 3
[X] Item 4
[ ] Item 5
I have two arrays:
$amenities
All items in the database are here.$related
All previously checked items are here. (in this case, two of them)
How can I walk the two arrays comparing them so if an item in $related
is found in $amenities
, it will print the box checked and if not, it will print it unchecked. This is my code relevant to that part.
$amenities (print_r)
Array
(
[0] => Array
(
[itemID] => 3
[itemName] => Crema Chantilly
)
[1] => Array
(
[itemID] => 4
[itemName] => Caribe Cooler
)
[2] => Array
(
[itemID] => 5
[itemName] => Cacahuates Japoneses
)
[3] => Array
(
[itemID] => 6
[itemName] => Cerveza Sol (lata)
)
[4] => Array
(
[itemID] => 7
[itemName] => Chocolate derretido
)
)
$related (print_r)
Array
(
[0] => Array
(
[itemID] => 3
[itemName] => Crema Chantilly
)
[1] => Array
(
[itemID] => 4
[itemName] => Caribe Cooler
)
)
As you can see, there are two items in $related
that match two items in $amenities
.
What I'm trying here is something like this:
<?php foreach ($related as $single) : ?>
<?php foreach ($amenities as $amenity) : ?>
<?php if ( $single === $amenity) : ?>
<input type="checkbox" class="left" checked="yes" name="amenities[]" value="<?=$amenity['itemID']?>">
<label class="checkbox"><?=$amenity['itemName']?></label>
<?php else : ?>
<input type="checkbox" class="left" name="amenities[]" value="<?=$amenity['itemID']?>">
<label class="checkbox"><?=$amenity['itemName']?></label>
<?php endif ?>
<?php endforeach;?>
<?php endforeach;?>
But, the results are being duplicated for the full options list. I'm getting this:
[X] Item 1
[ ] Item 2
[ ] Item 3
[ ] Item 4
[ ] Item 5
[ ] Item 1
[ ] Item 2
[X] Item 3
[ ] Item 4
[ ] Item 5
And I need to get
[X] Item 1
[ ] Item 2
[X] Item 3
[ ] Item 4
[ ] Item 5
Maybe it's something easy to do but I can't figure out how to get this done. Maybe I am taking the wrong approach with the two foreach
?