I have 2 arrays, and I am trying to find out which checkboxes should be checked and which not. I do get correct results, but if 2 checkboxes should be checked, I get 2 sets of checkboxes, if 3 should be checked i get 3 set of checkboxes and so on... I make a numerous attempts to avoid that using break and continue statements, without success.
Here is the code:
<?php
foreach ($rooms as $room) {
foreach ($searchQuerySelectedRooms as $selRoom) {
if ($room['roomID'] != $selRoom) {
?>
<input type="checkbox" name="rooms[]" value="<?php echo $room['roomID']; ?>" style="float:left;width:20px; margin-right:10px;"/>
<?php
} else {
?>
<input type="checkbox" name="rooms[]" value="<?php echo $room['roomID']; ?>" style="float:left;width:20px; margin-right:10px;" checked="checked"/>
<?php
}
}
}
?>
Array $rooms
prints the following:
Array
(
[0] => Array
(
[roomID] => 2
[hotelID] => 10
[roomtypeID] => 1
[roomNumber] => 1
)
[1] => Array
(
[roomID] => 3
[hotelID] => 10
[roomtypeID] => 1
[roomNumber] => 2
)
[2] => Array
(
[roomID] => 4
[hotelID] => 10
[roomtypeID] => 2
[roomNumber] => 3
)
[3] => Array
(
[roomID] => 5
[hotelID] => 10
[roomtypeID] => 2
[roomNumber] => 4
)
)
While array $searchQuerySelectedRooms
prints the following:
Array
(
[0] => 2
[1] => 3
[2] => 4
)
Any help will be deeply appreciated.
Regards, John
please check this code
<?php
foreach ($rooms as $room) {
if (in_array($room['roomID'], $searchQuerySelectedRooms)) {
$checker = 'checked="checked"';
} else {
$checker = '';
}
echo '<input type="checkbox" name="rooms[]" value="' . $room['roomID'] . '" style="float:left;width:20px; margin-right:10px;" ' . $checker . '/>';
}
?>
This can be reduced down to just a couple of lines (n.b. I've reformatted to make it easier to read on SO):
<?php foreach ($rooms as $room) { ?>
<input type="checkbox"
name="rooms[]"
value="<?= $room['roomID']; ?>"
style="float:left;width:20px; margin-right:10px;"
<?= in_array($room['roomID'], $searchQuerySelectedRooms)? 'checked="checked"':''?>/>
<?php } ?>
Take note of the short syntax to echo the result of a statement ( ) and also the short syntax for an if statement ( condition ? true output : false output )