0

I am using the PHP function imap_open with this to get the headers of each email:

$header=imap_headerinfo($inbox,$email_number);

i then run a foreach loop on the CC'd email addresses:

foreach ($header->cc as $cc_extra) {

}

how can i check if there is anything in $header->cc before i run the foreach loop?

Note: - the $inbox is the connection string for the mailbox - the $email_number is the email number for each email

charlie
  • 1,356
  • 7
  • 38
  • 76
  • possible duplicate of [cleanest way to skip a foreach if array is empty](http://stackoverflow.com/questions/3446538/cleanest-way-to-skip-a-foreach-if-array-is-empty) – adamdunson Jan 07 '14 at 17:43

2 Answers2

0

You could use a combination of isset and is_array like so:

$header=imap_headerinfo($inbox,$email_number);
// ...
if(isset($header->cc) && is_array($header->cc)) {
  foreach ($header->cc as $cc_extra) {
  }
}

isset will test that the variable has been set as is not null.
is_array will test that the variable is actually an array.

EDIT

Alternatively, as seen in this SO answer, you can explicitly cast the variable as an array inside your foreach, e.g.,

foreach ((array)$header->cc as $cc_extra) {
}
Community
  • 1
  • 1
adamdunson
  • 2,635
  • 1
  • 23
  • 27
0

I use next code:

$connection = imap_open("{192.168.1.170:993/imap/ssl/novalidate-cert}INBOX", $send_from_our, $send_from_pass) or die('Cannot connect to your sever: ' . imap_last_error());
$emails = imap_search($connection, 'UNSEEN');
$unread = 0;
$count = imap_num_msg($connection);

for ($msgno = 1; $msgno <= $count; $msgno++) {
    $cc='';
    $to='';
    $headers = imap_headerinfo($connection, $msgno);           
    if ($headers->Unseen == 'U') {
        $unread++;
        if (isset($headers->cc) && is_array($headers->cc)) {
            foreach ($headers->cc as $cc_extra) {
                $mailbox_cc=strtolower($cc_extra->mailbox);
                $host_cc=strtolower($cc_extra->host);
                $cc .= $mailbox_cc . "@" . $host_cc .',';
            }
            $cc= rtrim($cc, ',');
        }
        if (isset($headers->to) && is_array($headers->to)) {
            foreach ($headers->to as $to_extra) {
                $mailbox_to=strtolower($to_extra->mailbox);
                $host_to=strtolower($to_extra->host);
                if ($mailbox_to=='$MY_EMAIL_NAME' and $host_to='$MY_HOST_NAME') {
                    continue;
                }
                $to .=$mailbox_to . "@" . $host_to.',';
            }
            $to=rtrim($to, ',');
        }
        $fromaddr = $headers->from[0]->mailbox . "@" . $headers->from[0]->host;
        $full_reply_to=rtrim($fromaddr.','.$cc.','.$to, ',');

This code recieve all unread email from maibox, and put all adress from CC and TO (exclude my self address) for each email to $full_reply_to

Vadim Nosyrev
  • 113
  • 1
  • 9