skip to Main Content

I have this code

foreach ($codes as $code => $total)  {
    printf("%s <font color='blue'><b>Total clicks = %d<br></b></font>", $code, $total); 
}

Which gives me the output

01 output 1 Total clicks = 1
02 output 2 Total clicks = 1
03 output 3 Total clicks = 1
03 output 4 Total clicks = 1
03 output 5 Total clicks = 1

etc

How can I assign the output to a variable to use in a mailout i.e.

$message5 = each line of output

so that my mail out shows the same ouput

01 output 1 Total clicks = 1
02 output 2 Total clicks = 1
03 output 3 Total clicks = 1
03 output 4 Total clicks = 1
03 output 5 Total clicks = 1

a member suggested using sprintf so I tried this

foreach ($codes as $code => $total)  {
    printf("%s <font color='blue'><b>Total clicks = %d<br></b></font>", $code, $total); 
    $message5 = sprintf("%s <font color='blue'><b>Total clicks = %d<br></b></font>", $code, $total); 
}

But it only gives me the last line of output
user3783243 suggests that

$message5 =  overwrites on every iteration 

How can I stop the overwrite?

2

Answers


  1. Let’s try with this

        $message = '';
                
        foreach ($codes as $code => $total)  {
            $message .= sprintf("%s <font color='blue'><b>Total clicks = %d<br></b></font><br>", $code, $total); 
        }
    
        echo $message;
    
    Login or Signup to reply.
  2. As I adhere from the comments and the questions you want to concatenate each message separately

    $final_message = []; 
    foreach ($codes as $code => $total)  {
        printf("%s <font color='blue'><b>Total clicks = %d<br></b></font>", $code, $total); 
       // message5 or 4 it doesn't matter it will get each message on each iterate
        $message5 = sprintf("%s <font color='blue'><b>Total clicks = %d<br></b></font>", $code, $total); 
        $final_message[] = $message5;
    }
    var_dump($final_message); // $final_message[0], $final_message[1] etc..
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search