简体   繁体   中英

Count specific condition within an if statement

In a PHP script, I perform a specific task in batches of ITERATIONS_PER_LOOP . Within the foreach loop that performs the task, I have an if statement with some conditions. The thing is I want to count the times 2 of those conditions (all of them are 3) are met. But I can't seem to find a (elegant) way to do that. Please take a look at the code below.

So my original was this:

    if (in_array($publication, $blacklist) || !remote_file_exists($remote['frontpage']['url']) || $iterations >= ITERATIONS_PER_LOOP) {
        continue;
    }

which I changed to the following:

    if ($skip = (in_array($publication, $blacklist) || !remote_file_exists($remote['frontpage']['url'])) || $iterations >= ITERATIONS_PER_LOOP) {
        if ($skip) {
            $skipped++;
        }

        continue;
    }

The idea was to assign the condition of the first two statements being met to a var, then count the times that var - $skip - was assigned a true value. However this doesn't seem to work as expected, as it counts not only the occurrences of a non-existent file or a blacklisted file, but also the remaining iterations that will occur in next loops.

So, let's say we have a batch of 100 items to process and the ITERATIONS_PER_LOOP is set to 10.

Let's also say that in the first 2 batches we didn't sequentially meet a blacklisted item, nor an item without a valid image. Then the $skipped counter should be 0.

In the 3rd batch let's assume we hit 1 blacklisted item and 2 items with missing images. In this batch the counter should be 3.

Ah, I forgot to mention that at each iteration, the batch starts from the beginning, and already done items are taken care at another part of the script.

So, in the 4th batch, we found 1 more blacklisted item, and 6 items with a missing image. Now the counter should read 10 (3 from the previous batch plus 7 from this one).

Etc etc...

Instead, the code above for the first run says skipped 90 (remember the ITERATIONS_PER_LOOP is set to 10). In the 2nd batch it shows 80.

In the 3rd batch it'd show 67 (it would show 70 but subtracts the 3 really skipped ones from it, so it shows 67)...

What am I doing wrong here?

|| has higher precedence than = , so even with your parentheses, you're still sucking up the whole statement. Just move the open paren a little bit:

    if (($skip = in_array($publication, $blacklist) || !remote_file_exists($remote['frontpage']['url']))
         || $iterations >= ITERATIONS_PER_LOOP) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM