0

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.

1
  • 8
    You're computing $x only once, before your loop. You'll want the random number generation to occur at every iteration. Commented Oct 28, 2019 at 14:15

2 Answers 2

2

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.

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

3 Comments

You need to close that div.
downvoted since your code overrides the $color_array with each iteration, absolutely no reason to do it !
Thanks for the suggestion, I didn't notice that :)
-1
<?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>';
        }
?>

1 Comment

Downvoted because it makes no attempt to explain the code you just wrote. Fix that and I will gladly remove it :)

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.