[Chartjs]-Chart.js loading data colors from PHP

2👍

The only reason I can think of for this not to work is if your PHP $myColors variable is either an object or a non-continuous array (ie you have skipped keys).

The former is unlikely so assuming the latter, eg

$myColors = [0 => 'red', 1 => 'blue', 3 => 'green'];

You would get a JS object like

{"0":"red","1":"blue","3":"green"}

The solution is to create an array with sequential keys. If you’re building one up, don’t directly assign index values, use

$myColors[] = 'blue'

instead to push new values.

If this cannot be avoided, use array_values() to create an indexed array

var myColors = <?= json_encode(array_values($myColors)) ?>;

Leave a comment