0

I have the following code:

echo "Hi " . $firstName . ",  <br /><br /> text <br /> <br />";
$i = 0;
foreach ($urls as $key) {
print_r ('<a href="' . ($key) . '">');
print_r($names[$i] . "</a>");
echo "<br /> <br />";
$i++;
}
echo "text, <br /><br /> text";

This prints out a message with a list of links generated by the foreach loop. I'd like to store the result in a variable (which I use as the body of an email).

4 Answers 4

1

You can do as

$body = '';
foreach ($urls as $key) {
$body .= '<a href="' . ($key) . '">';
$body .= $names[$i] . "</a>";
$body .= "<br /> <br />";
$i++;
}

Here initializing a var $body and inside the loop concatenating the result into body so that you can use it later.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this, Here added $data variable and $data .= concatenated the results in variable.

    $data = "Hi " . $firstName . ",  <br /><br /> text <br /> <br />";
    $i = 0;
    foreach ($urls as $key) {
        $data .='<a href="' . ($key) . '">'.$names[$i] . "</a><br /> <br />";
        $i++;
    }
    $data .="text, <br /><br /> text";      
    echo $data;

Comments

0

Just concat the new strings with a summation of the previous strings.

$output = "Hi $firstName,<br/><br/>text<br/><br/>";
$i = 0;
foreach ($urls as $key) {
    $output .= '<a href="' . $key . '">' . $names[$i] . "</a><br/><br/>";
    $i++;
}
$output .= "text,<br/><br/>text";
echo $output;

Comments

0

I would use the ob_* functions. Specifically ob_start, ob_get_contents, and ob_end_clean

In your case, it would be:

ob_start();

echo "Hi " . $firstName . ",  <br /><br /> text <br /> <br />";
$i = 0;
foreach ($urls as $key) {
    print_r ('<a href="' . ($key) . '">');
    print_r($names[$i] . "</a>");
    echo "<br /> <br />";
    $i++;
}
echo "text, <br /><br /> text";

$body = ob_get_contents();
ob_end_clean();

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.