php - Comparing array values in nested foreach -
i've 2 arrays:
$rooms = [1,2,3,4,5,6,7,8,9]; $reserved_rooms = [4, 7];
i print array this:
1 2 3 room 4 reserved 5 6 room 7 reserved
her code:
$rooms = [1,2,3,4,5,6,7,8,9]; $reserved_rooms = [4, 7]; foreach($rooms $key=>$val){ foreach($reserved_rooms $val2){ if($val == $val2){ echo $val2." room reserved"; } else echo $val."<br>"; } }
the result is:
1 1 2 2 3 3 4 room reserved4 5 5 6 6 7 7 room reserved8 8 9 9
you need move echo
outside loop.
$rooms = [1,2,3,4,5,6,7,8,9]; $reserved_rooms = [4, 7]; foreach($rooms $key=>$val){ $isreserved = false; // add foreach($reserved_rooms $val2){ if($val == $val2){ $isreserved = true; break; // reserved, no need check other values } } if ($isreserved) { // decide whether reserved or not echo $val." room reserved"; } else { echo $val."<br>"; } }
Comments
Post a Comment