Random color in foreach loop

4 posts by 2 authors in: Forums > CMS Builder
Last Post: September 11, 2017   (RSS)

By Mikey - September 10, 2017

Got this figured out. Not going to say it's perfect, but it seems to be working so far.

<?php foreach ($namesRecords as $record): ?>
       <?php 
        {
             $r = rand(0,255); 
             $g = rand(0,255); 
             $b = rand(0,255); 
             $color = dechex($r) . dechex($g) . dechex($b);
        }
        ?>
             <?php echo "rgb(".$r.",".$g.",".$b.")"; ?>
  <?php endforeach ?>

Zicky

By Dave - September 11, 2017

Nice work! 

Dave Edis - Senior Developer
interactivetools.com

By Mikey - September 11, 2017

Thanks Dave,

Here's what I came up with as the final solution for random RGB colors. This has a way to control the opacity of the colors displayed.

<?php foreach ($nameRecords as $record): ?>
     <?php {
            $r = rand(0,255); $g = rand(0,255); $b = rand(0,255); $opacity = 0.4;
     } ?>
            '<?php echo "rgba(".$r.",".$g.",".$b.",".$opacity.")"; ?>',
<?php endforeach ?>

I'm using this in some charts I'm building using Charts.js "http://www.chartjs.org".

Zicky