2

I have a variable called $to. I want this variable to contain data separated by a comma like below:

$to='[email protected], [email protected]';

If there is only one email there will no comma; if there are multiple emails there will not be a comma after the last email.

2
  • You can use group_concat if you like to concatenate column values in mysql. Commented Jul 26, 2017 at 9:43
  • 1
    A PHP solution would be the use of implode(',', $emails). Commented Jul 26, 2017 at 9:45

4 Answers 4

4

You can use explode to convert it into array. Then you can traverse from array

<?php
 $to='[email protected], [email protected]';
 $to_array = explode(",", $to);
 foreach ($to_array as $key => $value) {
   echo $value;
 }

If you want to do opposite you can use implode

$to_array = array('[email protected]', '[email protected]');
$to = implode(",",$to_array);
echo $to;
Sign up to request clarification or add additional context in comments.

2 Comments

This is the opposite of what the OP asks for. The goal is to get the string with the values, not to split them.
@TobiasF. read question heading. OP asked for how to loop data from database seperated with coma in php which I have explain. BTW I have edited both
2
try 
    $result = implode(',',$to);

Comments

2

use implode()

for example:

$emails = ["[email protected]","[email protected]","[email protected]"];

$to = implode(',',$a);

Comments

1

You can save all your eMails address in an array and then you can implode it with comma, it automatically handle all the cases

$addresses= array()
$addresses[] = '[email protected]';
$addresses[] = '[email protected]';
$to = implode(",",$addresses);

You will find in $to all your addresses separated by comma except the last one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.