user3386779
user3386779

Reputation: 7175

string concatenate for global variable

I have fetched the value from database using query and trace the variable using foreach. I want to get the mail id append with the variable $cc_test.

Initially the variable is empty. for first iteration [email protected] 2nd iteration [email protected] and for 3rd [email protected].

Finally I want to get [email protected],[email protected],[email protected], but now I get '[email protected],[email protected]'.

$cc_check is an indexed array print_r($cc_test) in for loop prints [email protected] for 1st and [email protected] for 2nd and so on.

$cc_check=asset_status_tracker::where('request_id','=',$data['id'])->where('status_before','!=',null)->get();
$cc_test=''; //dump requestor mail id
foreach($cc_check as $cc_inner){
    $cc_mail=$cc_inner->changed_by;
    print_r($cc_mail);
    $cc_test=users::where('id','=',$cc_mail)->first()->mail;
    $cc_test=$cc_test.','.$cc_test;
    //print_r($cc_test); 
}
print_r($cc_test); //[email protected],[email protected],[email protected]

Upvotes: 0

Views: 344

Answers (1)

mickmackusa
mickmackusa

Reputation: 47904

If I understand you, you don't need a counter, you just need to concatenate all of the values using commas as glue.

You can do this without excess commas or iterating conditions by running implode() after the loop is finished.

Save the emails in an array, and implode the array to generate a string of comma-separated values.

Code:

$emails=[];
foreach($cc_check as $cc_inner){
    $emails[]=users::where('id','=',$cc_inner->changed_by)->first()->mail;
}
$email_string=implode(',',$emails);
echo $email_string;

Upvotes: 1

Related Questions