How to create a dynamic color list for charts

How to create a dynamic color list for charts

Basically, I have a different value in my database, or each value contains every percentage and I need to show that percentage in a pie chart with different colors ....

This is a code example of a pie chart in a static way

<color value="#99CDFB"/>
<color value="#3366FB"/>
<color value="#0000FA"/>
<color value="#F8CC00"/>
<color value="#F89900"/>
<color value="#F76600"/>


but I need a dynamic path using PHP ( for loop / foreach ) like this

$color = "";
foreach($data as $data){
   echo '<color value=".$color."/>';


and i dont know to create a dynamic color list, also see screenshot for check enter image description here


source to share

2 answers

For a random string of colors, here's:

function randColor( $numColors ) {
    $chars = "ABCDEF0123456789";   
    $size = strlen( $chars );
    $str = array();
    for( $i = 0; $i < $numColors; $i++ ) {
        for( $j = 0; $j < 6; $j++ ) {
            $str[$i] .= $chars[ rand( 0, $size - 1 ) ];
    return $str;


Then in your function, use $colors = randColor( 6 );

to create a total of 6 different colors. After that, here's your color output method.

foreach( $colors as $codeColor ) {
    echo "<color value=\"#{$codeColor}\" />\n";




I would rather use aproach using dechex () . First, you need to prepare three random numbers 0-255, convert them to hex and join the string. Then you can also use the calculated numbers to assign the text color: black for lighter colors or white for darker ones, for example:

    if( ($r + $g + $b) / 3 > 126)


Another idea is to create random shaded colors. First you can generate three random numbers from 0 to say 40 for the first color, then the second color will be 40 to 80 and so on ...



All Articles