Random color in foreach loop

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

By Mikey - September 9, 2017 - edited: September 9, 2017

Anyone have any suggestions on how to get a random rgba() color in this foreach loop?

<?php if ($tagsToCount): ?>
         <?php  $maximumResults = 12;
        $resultCount = 0;
?>
  <?php $totalTagCount = array_sum($tagsToCount); ?>
    <?php
        arsort($tagsToCount);
                $tagsToCount = array_slice($tagsToCount, 0, 99);
    foreach ($tagsToCount as $key => $value): ?>
                'rgba(255, 99, 132, 0.2)', <<<<// I need this to be a random results.
<?php if (++$resultCount == $maximumResults) { break;}?>

  <?php endforeach ?>
<?php endif ?>

Thanks 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