I wrote this function to map value to a color
I am looking for some general feedback on how I can improve the efficiency of the function. and if there is better way to do it.
function getColor($value, $values_range, $opacity = '0.7') { $deltaS = ($values_range['max'] - $values_range['min']) / 2; $ds = ($value - $values_range['min']) / $deltaS; $nearest_color_index = floor($ds); $alpha = $ds - $nearest_color_index; $r = $g = $b = -1; $colors = [['r'=>255,'g' => 60,'b' => 40], ['r' => 255,'g' => 247,'b' =>40], ['r' => 12,'g' => 197,'b' => 17]]; if ($nearest_color_index != 2) { $r = round($colors[$nearest_color_index]['r'] + $alpha * ($colors[$nearest_color_index + 1]['r'] - $colors[$nearest_color_index]['r'])); $g = round($colors[$nearest_color_index]['g'] + ($alpha * ($colors[$nearest_color_index + 1]['g'] - $colors[$nearest_color_index]['g']))); $b = round($colors[$nearest_color_index]['b'] + $alpha * ($colors[$nearest_color_index + 1]['b'] - $colors[$nearest_color_index]['b'])); return "rgba($r,$g,$b,$opacity)"; } else { $r = round($colors[$nearest_color_index]['r']); $g = round($colors[$nearest_color_index]['g']); $b = round($colors[$nearest_color_index]['b']); return "rgba($r,$g,$b,$opacity)"; } }