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

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

I'm using $color inside a loop but in this simplistic way that my code is, the value of the variable can be repeated type 3, 3, 1 .

How do you make a value of 3 loops , 1, 2, 3 , 1, 3, 2 , 3, 2, 1 ... <

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; } ?>
    
asked by anonymous 07.12.2015 / 15:32

2 answers

7

I think you can change your approach to this code.

Define an array with colors in place of individual variables, with shuffle() shuffle the values, use echo with array_shift() to display the current value of the array and remove it, thus color / value does not repeat itself.

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

 $i = 0;
 while($i < 4){
    echo array_shift($cores) .'<br>';
    $i++;
 }
    
07.12.2015 / 15:46
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 this 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));
}

View a sample code output - PHPfiddle

    
07.12.2015 / 16:04