Created
September 6, 2024 19:23
-
-
Save BorisAnthony/ae1cd7d865cd09efad53ea3f8ce1445f to your computer and use it in GitHub Desktop.
PHP Cardinal Directions <-> Direction Degrees
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CardinalDirections | |
{ | |
private const CARDINALS = [ | |
'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', | |
'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW' | |
]; | |
public static function degreesToCardinals($degrees): array | |
{ | |
$degrees = fmod($degrees, 360); | |
if ($degrees < 0) { | |
$degrees += 360; | |
} | |
$index16 = (floor(($degrees / 22.5) + 0.5)) % 16; | |
$index8 = (floor(($degrees / 45) + 0.25)) % 8; | |
return [ | |
'16point' => self::CARDINALS[$index16], | |
'8point' => self::CARDINALS[$index8 * 2], | |
'degrees' => $degrees | |
]; | |
} | |
public static function cardinalToDegrees(string $cardinal): ?float | |
{ | |
$index = array_search(strtoupper($cardinal), self::CARDINALS); | |
if ($index === false) { | |
return null; | |
} | |
return $index * 22.5; | |
} | |
} | |
// Usage examples: | |
$degrees = -1235.4567; | |
$result = CardinalDirections::degreesToCardinals($degrees); | |
echo "Degrees Input: $degrees\n"; | |
echo "Degrees Calculated: {$result['degrees']}\n"; | |
echo "16-point: {$result['16point']}\n"; | |
echo "8-point: {$result['8point']}\n"; | |
$cardinal = 'NNW'; | |
$degrees = CardinalDirections::cardinalToDegrees($cardinal); | |
echo "\nCardinal: $cardinal\n"; | |
echo "Degrees: " . ($degrees !== null ? $degrees : "Invalid direction") . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment