Jump to content

still afraid of foreach


nickelus

Recommended Posts

heres an example and you're right but i cant think of where else i would set the variable when i am try to use the results in a table as (echo $each)

while($row=mysql_fetch_array($widgets)){
$each="<tr>
<td>".$row[0]."</td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
<td>".$row[4]."</td>
<td>".$row[5]."</td></tr>";}

You need to echo each "row" or set of data within the loop... if you wait and echo or print it outside of the loop, the loop runs and overwrites its variables from the last time around, leaving you with the last item in the set like:

 

$items = range(1,50);

echo "Before the loop<br />";
foreach($items as $k => $v) {

echo $v."<br />";

}

echo "After the loop";

 

Or in your example

echo "<table>";
while($row=mysql_fetch_array($widgets)){
$each="<tr>
<td>".$row[0]."</td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
<td>".$row[4]."</td>
<td>".$row[5]."</td></tr>";
echo $each;
}
echo "</table>";

heres an example and you're right but i cant think of where else i would set the variable when i am try to use the results in a table as (echo $each)

while($row=mysql_fetch_array($widgets)){
$each="<tr>
<td>".$row[0]."</td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
<td>".$row[4]."</td>
<td>".$row[5]."</td></tr>";}

 

That's because a while loop functions differently than a foreach loop. A while loop continues as long as the statement is true (or rather "while it's true it continues"). mysql_fetch_array() has an internal cursor that it moves forward each time you call it. As long as you've not exceeded the amount of rows returned it will return a value that can evaluate to true. That is why you can get all the rows using while, and why it will not work with foreach (because foreach takes a preexisting array and iterates over all the elements).

 

If you wanted to output all the fields in a row you could do like this:

while ($row = mysql_fetch_array($widgets)) {
echo '<tr>';
foreach ($row as $field) {
	echo '<td>' . $field . '</td>';
}
echo '</tr>';
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.