Anyway to make a php function out of this? It seems the second set of variables kills any function I try to write.
开发者_运维知识库 $flow = (15);
$low = (10);
$good =(20);
$high =(30);
if ($flow <= $low)
$class = "tdy";
else if (($flow > $low) && ($flow <= $good))
$class = "tdg";
else if ($flow >= $high)
$class = "tdr";
I've tried to make a function with this but it just fails to the high variable. Alone the if else statement runs fine with the variables. It would save a ton of time if I could just reset the variables and call the if else statement with a function on each instance.
I think your logic can be more simpler:
function getColor($flow, $low, $good) {
if ($flow <= $low)
return "tdy";
if ($flow <= $good)
return "tdg";
return "tdr";
}
Since the second check ($flow > $low) in the first else if is useless because if that was true, the first if was executed. And of course, if the first else if not get executed, the only option is the last else if which makes it useless to check on.
function getColor($flow, $low, $good, $high) {
if ($flow <= $low)
return "tdy";
else if (($flow > $low) && ($flow <= $good))
return "tdg";
else if ($flow >= $high)
return "tdr";
}
<?php
$def = array(10=>'tdy',20=>'tdg',30=>'tdr');
foreach(array(9,10,11,19,20,21,29,30,31) as $i) {
printf("%02d %s\n", $i, foo($i, $def));
}
function foo($val, $sel) {
foreach($sel as $k=>$v) {
if ( $val<=$k ) {
return $v;
}
}
return end($sel);
}
prints
09 tdy
10 tdy
11 tdg
19 tdg
20 tdg
21 tdr
29 tdr
30 tdr
31 tdr
精彩评论