You shouldn't call imap_expunge until before closing the connection. imap_delete tags a message for deletion, imap_expunge deletes all tagged messages. i.e.:
for ($i = 0; $i < $num; $i++) {
imap_delete($box, $i);
}
imap_expunge($box);
imap_expunge should not be in your inner loop.