What are alternative approaches to using switch statements in PHP for conditional color assignment based on temperature ranges?
Switch statements can become cumbersome and hard to maintain when dealing with multiple conditions, such as assigning colors based on temperature ranges. An alternative approach is to use an associative array where the keys represent the temperature ranges and the values represent the corresponding colors. This allows for easier management of conditions and provides a more flexible solution.
$temperature = 25; // temperature value
$colorRanges = [
'0-10' => 'blue',
'11-20' => 'green',
'21-30' => 'yellow',
'31-40' => 'orange',
'41-50' => 'red'
];
$assignedColor = '';
foreach ($colorRanges as $range => $color) {
list($min, $max) = explode('-', $range);
if ($temperature >= $min && $temperature <= $max) {
$assignedColor = $color;
break;
}
}
echo "Temperature: $temperature degrees, Color: $assignedColor";