Question

I created the available seat with a for loop below:

<?php

$seats = 7;

for ($i=1; $i <= $seats; $i++) {

?>

<div class='col-xs-6'>
  <div class='well text-center' id='<?php echo $i ?>'>
    Seat No: <?php echo $i ?>
  </div>
</div>

<?php

}

?>

And I want to add a booked class if the $i variable matches with the $k variables which taken from the booked seat array elements below:

$booked_seat = array('1','4','5','6','7');

the result:

Array
(
    [0] => 1
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 7
)

So I did this:

<?php

$seats = 7;

for ($i=1; $i <= $seats; $i++) {

?>

<div class='col-xs-6'>
  <div class='well text-center <?php echo ($i == $booked_seat[$i-1]) ? 'booked' : '' ?>' id='<?php echo $i ?>'>
    Seat No: <?php echo $i ?>
  </div>
</div>

<?php

}

?>

And i get the offset Error because the $booked_seat is not much as the $seats loop, how to limit the loop so it will not offset?

Thank you before

Was it helpful?

Solution

Try this:

$seats = 7;

for ($i=1; $i <= $seats; $i++) {


?>

<div class='col-xs-6'>
  <div class='well text-center <?php echo (in_array($i, $booked_seat)) ? "booked" : "" ?>' id='<?php echo $i ?>'>
    Seat No: <?php echo $i ?>
  </div>
</div>

<?php

}

?>

warning: code is untested.

OTHER TIPS

You could always flip the $booked_seat array, then test for the existence of the array element using isset(). Something like this:

<?php

$seats = 7;
$booked_seat = array('1','4','5','6','7');
$booked_a = array_flip($booked_seat);

for ($i=1; $i <= $seats; $i++) {
  printf("seat: %d%s\n", $i, isset($booked_a[$i]) ? " booked" : "");
}

(This was my test, you can add your HTML to suit.)

Example: http://3v4l.org/5npsm

You should use the method sizeof().

So:

$num_seats = sizeof($seats);

Then a for loop with this.

for($i = 0; $i < $num_seats; $i++){ //code }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top