PHP - imap count unseen emails gives always '1' as result

503 views Asked by At

Trying to count the unseen emails in my email box, the script I have does the counting however, when there are no unseen emails the result is always 1 and no 0. Any idea why?

here the code I have so far.

php:

    $hostname = '{imap.example.com:993/imap/ssl}INBOX';
    $username = '[email protected]';
    $password = 'mypass';
    $imap = imap_open($hostname, $username, $password) or die("imap connection error");
    $result = imap_search($imap, 'UNSEEN');
    $new_inbox_msg = count($result);
    echo $new_inbox_msg
1

There are 1 answers

10
arkascha On BEST ANSWER

imap_search() returns an array, not a number, according to the documentation.

So instead you need:

$result = imap_search($imap, 'UNSEEN');
echo count($result);

OK, sorry, miss interpreted the documentation myself. So here an explanation of your issue: the function indeed does return an array, but an array holding one result (count) per search attribute you handed over. Since you only specify a single attribute ('UNSEEN') you always get a single element in the array. That elements value is the number of messages matching that search criteria.

Therefore the correct usage should be:

$result = imap_search($imap, 'UNSEEN');
if (is_array($result) && isset($result[0])) {
    echo count($result[0]);
} else {
    echo "Failed to query number of messages\n";
}