How to assign a different value to the variable in each loop?

Asked

Viewed 1,145 times

5

$azul = "#4285f4"; // AZUL
$verde = "#34a853"; // VERDE
$amarelo = "#fbbc05"; // AMARELO
$vermelho = "#ea4335"; // VERMELHO
$color = rand(1, 4);

I’m using $color within a loop but in this simple way that is my code, the value of the variable cited can be repeated like 3, 3, 1.

How to make in a space of 3 loops, the value is not repeated by forming sequences of the type 1, 2, 3, 1, 3, 2, 3, 2, 1, 3, 1, 2 etc. ...

while ( $destaques->have_posts() ) { $destaques->the_post(); 

     if($color == 1) { $color = $azul; }
     elseif ($color == 2) { $color = $verde; }
     elseif ($color == 3) { $color = $amarelo; }
     elseif ($color == 4) { $color = $vermelho; } ?>

2 answers

7


I think you can change your approach to this code.

Set an array of colors instead of individual variables, with shuffle() shuffle values, use the echo with array_shift() to display the current value of the array and remove it, so the color/value is not repeated.

<?php
$cores = ["#4285f4", "#34a853", "#fbbc05","#ea4335"];
shuffle($cores);

 $i = 0;
 while($i < 4){
    echo array_shift($cores) .'<br>';
    $i++;
 }
  • I have a serious problem learning arrays @rray ... Don’t give private lessons by Skype, Teamviewer or something? Perfect solution.

  • @Marcosvinicius, haha can talk about it if you are interested.

2

Example with a continuous rotation

$arr = array(1, 2, 3, 4); //aqui seriam as 4 cores.
$data = range(1, 100); // isso aqui simula os dados onde o laço de repetição percorre.

foreach ($data as $v)
{
    echo '('.$v.') : '.implode('.',array_slice($arr, 0, 3)).PHP_EOL.'<br />';

    array_push($arr, array_shift($arr));
}

Let’s see it in practice, with colors:

    $arr = array('4285f4', '34a853', 'fbbc05', 'ea4335');
//$arr = array(1, 2, 3, 4);
$data = range(1, 100);

foreach ($data as $v)
{
    //echo '('.$v.') : '.implode('.',array_slice($arr, 0, 3)).PHP_EOL;
    for ($i = 0; $i < 3; $i++)
        echo '<div style="background-color:#'.$arr[$i].'; display:inline-block; padding:20px; margin:0px; border:0px;">########</div>';

    echo '<br />';
    array_push($arr, array_shift($arr));
}

See an example of code output - Phpfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.