Alvaro Hernandorena
Alvaro Hernandorena

Reputation: 610

php go back one time in for loop

I have a function that checks emails from an imap server using php imap functions.

That functions checks all emails in a folder starting from 1 to x=total messages.

and inside that function there is a script that checks if the emails is an spam email, and if it is it delete it from the server.

When the spam mail is deleted the total messages on the folder is reduced by 1. And the for loop skips the next email.

example, inbox haves 10 emails, and the for loop starts in 1 to 10. If email 5 is found to be spam it gets deleted, but when that happens the email that was 6 becomes 5, and the for loop skips it because it tries to read email 6.

How can I go back by 1 when that happens?

for(var $i = 1; $i<=$totalMessages; $i++){
  if(isSpam()==true){
    //delete from imap server
    $i = $i-1 //does not work, $i = $i -2 does not work eighter
  }
}

Upvotes: 0

Views: 127

Answers (2)

RST
RST

Reputation: 3925

in this case you are better of with a while loop

$index = 1;
while( $index <= $totalMessages) {
  if(isSpam()==true){
    //delete from imap server
  } else {
    $index++;
  }
}

Upvotes: 2

trincot
trincot

Reputation: 350300

This kind of problem is often solved by iterating backwards:

for(var $i = $totalMessages; $i>= 1; $i--){
    // ...etc
}

Upvotes: 2

Related Questions