I'm trying to create a function that returns the compass points given the angle from 0 to 360 degrees, and came across this function. It works, except when the angle is 0... And I cannot understand why this code does not work:
echo rosaventos(0);
function rosaventos($grau,$slim=true){
switch($grau) {
case in_array($grau, range(0,22,1)):{
$prnt = "N";
break;
}
case in_array($grau, range(23,67,1)):{
$prnt = "NE";
break;
}
case in_array($grau, range(68,112,1)):{
$prnt = "E";
break;
}
case in_array($grau, range(113,157,1)):{
$prnt = "SE";
break;
}
case in_array($grau, range(158,202,1)):{
$prnt = "S";
break;
}
case in_array($grau, range(203,247,1)):{
$prnt = "SO";
break;
}
case in_array($grau, range(248,292,1)):{
$prnt = "O";
break;
}
case in_array($grau, range(293,337,1)):{
$prnt = "NO";
break;
}
case in_array($grau, range(338,360,1)):{
$prnt = "N";
break;
}
default: {
$prnt = "-?-";
}
}
if($slim){
return $prnt;
}else{
return $prnt."-Extended";
}
}
The result is
NE, but it should be
N.
Can anybody explain why, and how to fix it?
Thanks
EDIT 1
Established that I made an error in the code, and the conditions should be like:
(...)
swich(true) {
(...)
and it's an inefficient way of doing things: I found that if I try
echo rosaventos("0");
using the original code, the result is the correct
N?!?!
Since you evenly divide your angles between the compass points, may I suggest you try a simple calculation and map lookup instead:
$dir = array("N", "NE", "E", "SE", "S", "SO", "O", "NO", "N");
$grau = 100;
$compass = $dir[floor( ($grau + 22.5) / 45 )];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With