Skip to content

Instantly share code, notes, and snippets.

@smallindine
Last active December 3, 2021 08:40
Show Gist options
  • Save smallindine/d227743c28418f3426ed36b8969ded1a to your computer and use it in GitHub Desktop.
Save smallindine/d227743c28418f3426ed36b8969ded1a to your computer and use it in GitHub Desktop.
php function to convert wind degrees to cardinal directions
<?php
function wind_cardinals($deg) {
$cardinalDirections = array(
'N' => array(348.75, 360),
'N' => array(0, 11.25),
'NNE' => array(11.25, 33.75),
'NE' => array(33.75, 56.25),
'ENE' => array(56.25, 78.75),
'E' => array(78.75, 101.25),
'ESE' => array(101.25, 123.75),
'SE' => array(123.75, 146.25),
'SSE' => array(146.25, 168.75),
'S' => array(168.75, 191.25),
'SSW' => array(191.25, 213.75),
'SW' => array(213.75, 236.25),
'WSW' => array(236.25, 258.75),
'W' => array(258.75, 281.25),
'WNW' => array(281.25, 303.75),
'NW' => array(303.75, 326.25),
'NNW' => array(326.25, 348.75)
);
foreach ($cardinalDirections as $dir => $angles) {
if ($deg >= $angles[0] && $deg < $angles[1]) {
$cardinal = $dir;
}
}
return $cardinal;
}
@taHC81
Copy link

taHC81 commented Feb 28, 2018

Twice declared 'N' leads to ignoring first declaration of 'N' => array(348.75, 360). Here's the workaround:

'N' => array(348.75, 361),
'N2' => array(0, 11.25),

if ($deg >= $angles[0] && $deg < $angles[1]) {
	$cardinal = str_replace("2", "", $dir);
}

@holawalt
Copy link

Hi I'm sorry if this is not the proper forum for this type of comment/question but I'm curious how this works.

From what I understand this is a function and for me to use it I have to call/invoke it by passing an argument through it. But I can't figure out what I'm doing wrong.

First, I'm pulling data from JSON (using json_decode to get the array) and assigning it to a variable in PHP:

$windDeg = $weatherArray['wind']['deg'];

Then I copied and pasted your code. After your function, I call your function and pass my variable through like this:

wind_cardinals($windDeg);

But when I:

echo $cardinal;

nothing happens. What do you think I'm doing it wrong? Does where my code goes matter?

@justamancr
Copy link

justamancr commented Jul 18, 2019

$directions = array('N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N2');
$cardinal = $directions[round($degrees / 22.5)];
if($cardinal == 'N2'){$cardinal='N';}

@rpiggott
Copy link

rpiggott commented Jan 28, 2020

PHP "switch" based version of the function
See My Pastebin.com Example

@alexbde
Copy link

alexbde commented Jul 6, 2020

function convertDegreesToWindDirection($degrees) {
	$directions = array('N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N');
	return $directions[round($degrees / 22.5)];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment