Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP switch() with in_array() and range() not working correctly [duplicate]

Tags:

function

php

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
?!?!
like image 842
Cerveira Avatar asked Oct 20 '25 23:10

Cerveira


1 Answers

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 )];
like image 110
mario Avatar answered Oct 22 '25 14:10

mario