Search code examples
phpimapphp-imap

What is the order of the e-mails found by imap_search?


I'm using imap_search to retreive all e-mails from a mailbox.

See: http://php.net/manual/en/function.imap-search.php

Is it safe to assume that imap_search() retreives the e-mail ordered by date, oldest first? It does seem so from my testing, but I can't find any documentation on the actual ordering.

If it is ordered by date, you could use array_reverse() and array_splice() to get the newest 10 or so.

Example code:

<?php
$conn   = imap_open('{imap.example.com:993/imap/ssl}INBOX', '[email protected]', 'pass123', OP_READONLY);

$msgnos = imap_search($conn, 'ALL');

?>

Solution

  • Rather than assuming the order that isn't specified in the documentation, and so could change at any version, sort it:

    imap_sort()

    imap_sort ( resource $imap_stream , int $criteria , int $reverse [, int $options = 0 [, string $search_criteria = NULL [, string $charset = NULL ]]] ) : array
    

    Gets and sorts message numbers by the given parameters.

    It even takes the search_criteria and allows you to reverse it in the same call.