2

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', 'foo@example.com', 'pass123', OP_READONLY);

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

?>
L.A. Rabida
  • 416
  • 3
  • 15
  • `imap_sort()` [See the manual](http://php.net/manual/en/function.imap-sort.php) – RiggsFolly Feb 18 '19 at 15:27
  • 1
    It is likely sorted by (U)ID, which correlates loosely with date received, but that breaks if messages are moved back and forth between folders. – Max Feb 18 '19 at 15:42

1 Answers1

2

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.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Indeed imap_sort would solve the problem, but it seems from https://stackoverflow.com/questions/4216934/imap-sort-limit-the-number-of-results that imap_sort() is very slow. That's why I wanted to circumvent imap_sort. But you're right, imap_search doesn't have a reliable sorting. – L.A. Rabida Feb 18 '19 at 15:38
  • 2
    imap_sort() isn't necessarily there. Some servers support it, others don't. It's not particularly slow though. – arnt Feb 18 '19 at 19:10