Find unread messages using PHP IMAP

Having reached the conclusion of my series on getting Google Analytics data by email I had an enquiry from someone asking how to find only the unread email messages using PHP IMAP. This is simple enough to do and can be done either when looping through the messages or using the imap_search function.

IMAP vs POP

Please note that the Unseen flag will only work if you are connecting to an IMAP mailbox and not when connecting using POP. POP servers have no concept of read and unread messages.