BekiTheMe BekiTheMe - 21 days ago 4x
PHP Question

Can I use an if on foreach in such a case?

I have a little problem, am trying to read values from mysql table. I have done research and could not find a definite or conclusive answer on this. I will describe the problem:

  1. select data from mysql table using a where e.g where gender=female.

  2. count the results and return the count - just to help know how many records were found

  3. compare a value in table, e.g 'taken' and 'available',

  4. if 'taken' = 'available'
    in the first record, go to next record(and compare again), if not perform a specific operation in this case can be update or insert or anything of that sort.

the first three are ok and the only problem is, part 4. Kindly help. This is a php problem. Looking forward for your help.


As was said, if you're merely going to skip the record then you may as well not retrieve them in the first place (and thus incur the overhead for having to extract them into PHP memory, etc):

SELECT * FROM `your_table` WHERE `gender` = 'female' AND `taken` = `available`;

However, if you have a specific reason to do this, you can merely do the following:

foreach ($hotels as $hotel) {
    // skip if the item is not available, logic can be changed if necessary
    if ($hotel->taken >= $hotel->available) continue;

    // do the other work here...

I interpreted your conditions a little here, assuming you wanted to skip people who aren't 'available'. Though it does look like you wanted the opposite, in which case you can switch the logic in the sql from != to = and in php from != to ==.

Updated: To reflect additional comments made.