Search code examples
phpwordpressforeachwordpress-plugin-creation

PHP - text not added to a variable inside foreach loop


I have this code in my WordPress plugin, it's supposed to get some data from database and after that send emails to different adresses with a common subject but different email body.

<?php

$pdv_subject = "Confirmation links from" . date('d-m-Y', time());
//
$pdv_message_a = "Salut!\n";
$pdv_email_a = 'user@example.com';
$pdv_headers_a[] = 'Cc: user@example.com';

//
$pdv_message_b = "Ciao!\n";
$pdv_email_b = 'user@example.com';
$pdv_headers_b[] = 'Cc: user@example.com';


//
$pdv_message_p = "Hello!\n";
$pdv_email_p = 'user@example.com';
$pdv_headers_p[] = 'Cc: user@example.com';


//
foreach( $results as $key => $val ){
    if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time()) && $val['pco'] === '650'){
        $pdv_message_a .= $val['link'] . "\n";
    } 
    //
    if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time()) && $val['pco'] === '620'){
        $pdv_message_b .= $val['link'] . "\n";
    }
    // 
    if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time()) && $val['pco'] === '660' ){
        $pdv_message_p .= $val['link'] . "\n";
    }
}

In the code I've omitted the wp_mail function, I've done a test and it's working fine. The only problem I have is that the $pdv_message_ that needs to be added inside the if statement will be not added, this will cause that the email will be sent without the links inside the body. I've done a var_dump() and I'm able to see the $val but why the links aren't added to the messages?


Solution

  • Aside from anything, I think I'd lay the code out like this

    foreach( $results as $key => $val ){
      if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time())) { 
        switch ($val['pco']) {
          case '620':
            $pdv_message_b .= $val['link'] . "\n";
            break;
          case '650':     
            $pdv_message_a .= $val['link'] . "\n";
            break;
          case '660':
            $pdv_message_p .= $val['link'] . "\n";
            break;  
            }
        }
    }
    

    (I'm not suggesting this is an answer to your problem, but it looks a lot nicer IMO and saves repeating all those identical if clauses.)