BekiTheMe BekiTheMe - 1 year ago 71
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download