Reputation: 35
I have a dynamic created by PHP which produces different squares with unique sizes and colors. Now, I want to output 100 of these squares to appear on the screen.
I have tried to put my code in a for
loop but it does not work:
<?php
$random_number = rand(10,100);
$color_array=array("yellow"=>"0","red"=>"1","green"=>"2","blue"=>"3","black"=>"4","brown"=>"5", "gray"=>"6");
$random_color = array_rand($color_array,1);
$x= '<div style="width:' . $random_number . 'px;height:' . $random_number . 'px;background-color:' . $random_color . '">';
for ($i = 0; $i <= 100; $i++) {
echo $x;
}
?>
There are no error messages, but only one square appears instead of 100.
Upvotes: 0
Views: 160
Reputation: 1619
Your variables $random_number, $random_color and $x
must be redeclared inside your loop.
The reason why you were seeing only one div
its because you forgot to close it. It was still generating them but inside one another.
<?php
$color_array=array("yellow"=>"0","red"=>"1","green"=>"2","blue"=>"3","black"=>"4","brown"=>"5", "gray"=>"6");
for ($i = 0; $i <= 100; $i++) {
$random_number = rand(10,100);
$random_color = array_rand($color_array,1);
$x= '<div style="width:' . $random_number . 'px;height:' . $random_number . 'px;background-color:' . $random_color . '"></div>';
echo $x;
}
?>
Otherwise you will only echo the same thing over and over again.
Upvotes: 2
Reputation: 1227
<?php
$color_array=array("yellow"=>"0","red"=>"1","green"=>"2","blue"=>"3","black"=>"4","brown"=>"5", "gray"=>"6");
for ($i = 0; $i <= 100; $i++) {
echo '<div style="width:' . rand(10,100) . 'px;height:' . rand(10,100) . 'px;background-color:' . array_rand($color_array,1) . '"></div></br>';
}
?>
Upvotes: -1