Search code examples
phpwordpresswp-mail

separate resulting values from a foreach with commas


I am saving values with add_user_meta within the same meta key.

What I need is to separate them with commas when getting them with foreach so I can send them by wp_mail.

I need something like this:


[email protected], [email protected], [email protected]

but when obtaining them directly, it returns them all together and glued.

some help?


$email = get_user_meta ($vendor_id, 'list_email', false);

foreach ($email as $emails) {
    echo $emails;
}

Result:


[email protected]@[email protected]

I tried some options, but the comma in front must be from the second email to be readable in wp_mail and I don't understand how to do it


Solution

  • You just need to append the "," in your loop and then remove the last "," using PHP rtrim() function. This code will do what you want:

    $email = ['[email protected]', '[email protected]', '[email protected]', '[email protected]'];
    $output = '';
    foreach ( $email as $emails ) {
      $output .= $emails . ', ';
    }
    $output = rtrim( $output, ', ' );
    echo $output;
    

    The output:

    [email protected], [email protected], [email protected], [email protected] 
    

    Edit: Thanks Vee for mentioning, there is way simpler solution for this that is Using implode() function, like this:

    $email = ['[email protected]', '[email protected]', '[email protected]', '[email protected]'];
    $output = implode(', ', $email);
    echo $output;
    

    Result:

    [email protected], [email protected], [email protected], [email protected]
    

    Tip: Always try to use proper names for your variables, here you should use $emails for the array of emails and $email for the single email item.