Trey Copeland
Trey Copeland

Reputation: 3527

How do I combine output of foreach into one variable?

I have to pass the content of a post into a method for it to post into Wordpress correctly. All the content posted will go into a $content variable thats passed to the method. How can I get the contents of a foreach loop into the $content variable?

<?php
$return = '';
foreach ($response['daily']['data'] as $cond) {

echo '<br /><br /><strong>' . date('l, F j, Y', $cond['time']) .'</strong><br />

<div id="dailysummary"><br />Daily Summary: ' . $cond['summary'] . '<br /><br /></div>

<table style="border:1px solid #ccc">

<tr>
<td>
High
</td>
<td>
'.round($cond['temperatureMax']).'
</td>
</tr>

<tr>
<td>
Low
</td>
<td>
'.round($cond['temperatureMin']).'
</td>
</tr>

<tr>
<td>
Chance of precip.
</td>
<td>
'.round($cond['precipProbability']).'%
</td>
</tr>   


<tr>
<td>
Wind speed
</td>
<td>
'.round($cond['windSpeed']).' mph
</td>
</tr>   



<tr>
<td>
Dewpoint.
</td>
<td>
'.round($cond['dewPoint']).'
</td>
</tr>   


<tr>
<td>
Humidity
</td>
<td>
'.round($cond['humidity']).'
</td>
</tr>   

</table>



<br /><br />';

}           

Upvotes: 0

Views: 147

Answers (3)

Adam Azad
Adam Azad

Reputation: 11297

Like so--using .= operator:

$content = '';

foreach ($response['daily']['data'] as $cond) {

   $content .= '<br /><br /><strong>' . date('l, F j, Y', $cond['time']).'</strong><br />

   <div id="dailysummary"><br />Daily Summary: ' . $cond['summary'] . '<br /><br /></div>

    <table style="border:1px solid #ccc">
    ... ';

}

print $content;

Upvotes: 0

Phiter
Phiter

Reputation: 14992

Do this:

$content = "";

foreach ($response['daily']['data'] as $cond) {

$content .= '<br /><br /><strong>' . date('l, F j, Y', $cond['time']) .'</strong><br />
[...]

You'll create an empty string and add more text to it on every loop.

Upvotes: 0

Marc B
Marc B

Reputation: 360602

Either build vars instead of echoing:

$html = '';
foreach(...) {
   $html .= '... build html here...';
}

Or keep your current code, and use output buffering:

ob_start();
foreach(...) {
   echo '... html goes here ...';
}
$html = ob_get_clean();

There's no right/wrong way of doing this. Either way you're going to end up with a chunk of html in memory.

Upvotes: 3

Related Questions