Reputation: 37
I'm probably making a very basic error but I'm quite new to this.
I have a table where I need to edit what is displayed in each box using variables but I'm having trouble with getting the outputs into the table. Experimentation helped me work out the first box but I can't get the second one working because I think the function is written incorrectly. I need a conditional loop that displays all even numbers between 10 and 20 (the code below doesn't have anything to do with even numbers at the moment I'm just trying to get it to work)
<?php
$random = rand() . srand(3034);
function loop() {
for ($i = 10; $i <= 20; $i++) {
$loop = $i;
return $loop;
}
}
echo "<table border='1'>
<tr>
<td>Box 1 - ".$random."</td>
<td>Box 2 - ".$loop."</td>
</tr>
</table> ";
?>
Any help is much appreciated.
Upvotes: 0
Views: 131
Reputation: 166
Try this:
<?php
function loop(){
$return = '';
for($i = 10; $i <=20; $i++){
$random = rand() . srand(3034);
if($i%2==0){
$return.='<tr>
<td>Box 1 - '.$random.'</td>
<td>Box 2 - '.$i.'</td>
</tr>';
}
}
return $return;
}
echo '<table>'.loop().'</table>';
Upvotes: 0
Reputation: 1833
You need to loop on the tags itself, because the return condition in the loop breaks it to only 1 iteration.
So you should do it like this:
echo "<tr>
<td>Box 1 - ".$random."</td>";
for ($i = 10; $i <= 20; $i++) {
echo "<td>Box 2 - ".$i."</td>";
}
echo"</tr>";
Upvotes: 2
Reputation: 32310
Additionally to my comment here is some more code:
<?php
$random = rand() . srand(3034);
function loop($randomNumber) {
for ($loop = 10; $loop <= 20; $loop++) {
echo
'<tr>' .
'<td>Box 1 - ' . $randomNumber . '</td>' .
'<td>Box 2 - ' . $loop . '</td>' .
'</tr>';
}
}
echo
'<table border="1">' .
loop($random) .
'</table>';
Upvotes: 0