-1

I am trying to run a for loop that checks for all the values in an array then run an if statement if any any value matches one that is in the array, it skips that value. I have this:

Total Seats

 10
$seats_arr = [1, 4, 7]
$result = mysqli_query($con, "SELECT * FROM trains WHERE id='$id'");

while ($row = mysqli_fetch_array($result)) {
    $total_seats = $row['seats'];
    $booked_seats = $row['booked_seats'];
    $viti = $row['viti'];
         
    $seats_arr = preg_split("/\,/", $viti);
    print_r($seats_arr);
                    
    ?>
    
    <select class="custom-select col-12" name="selected_seat">
        <option selected="" disabled>Choose your seat</option>
        <?php
         $N = $total_seats;
         foreach ($seats_arr as $seat) {            
         for($i=1; $i <= $N; $i++) {
                     
            if($i == $seat){
                continue;
             }
                      
         ?>
         <option value="<?php echo $i; ?>"><?php echo "Seat ", $i; ?></option>
          <?php
               } 
             }
           }
         ?>
     </select>

Desired Output

2, 3, 5, 6, 8, 9, 10
Billy Dan
  • 29
  • 1
  • 8
  • Post sample of the array and desired output – Kevin Gales May 08 '21 at 11:17
  • Firstly foreach ($seats_arr as $food) stores its values in $food and this variable is not called inside the loop. secondly the for loop inside the foreach is not necessary. try to be more explicit to get help – Bristol May 08 '21 at 11:24
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 08 '21 at 12:00

1 Answers1

1

Since well you are dealing with just numbers...this should work just fine

$range = range(1,$total_seats);
$seats_arr = [1, 4, 7];

$newunselected = array_diff($range,$seats_arr); //Your new array you can foreach this

print_r($newunselected); 
Kevin Gales
  • 532
  • 4
  • 9