Friday 26 June 2015

Get Closest Number

Simple PHP function that returns the closest number. The function receives two parameters: an array with numbers, and the number. Compares that number with the numbers from array, than returns the closest number from array.
<?php
// retutns the number from $array closest to $nr
function getClosestNr($array, $nr) {
  // PHP-MySQL Course - http://coursesweb.net/php-mysql/
  sort($array);      // Sorts the array from lowest to highest

  // will contain difference=>number (difference between $nr and the closest numbers which are lower than $nr)
  $diff_nr = array();

  // traverse the array with numbers
  // stores in $diff_nr the difference between the number immediately lower / higher and $nr; linked to that number
  foreach($array AS $num){
    if($nr > $num) $diff_nr[($nr - $num)] = $num;
    else if($nr <= $num){
      // if the current number from $array is equal to $nr, or immediately higher, stores that number and difference
      // and stops the foreach loop
      $diff_nr[($num - $nr)] = $num;
      break;
    }
  }
  krsort($diff_nr);        // Sorts the array by key (difference) in reverse order
  return end($diff_nr);    // returns the last element (with the smallest difference - which results to be the closest)
}

// Example
$numbers = array(-8, -3, 0, 5.8, 12, 9, 2.1);
$nr1 = -6;
$nr2 = 3;
$nr3 = 9;

// output closest number fo $nr1, $nr2, $nr3
echo getClosestNr($numbers, $nr1);      // -8
echo getClosestNr($numbers, $nr2);      // 2.1
echo getClosestNr($numbers, $nr3);      // 9
?>
Here's a practical usage of this function. I used the getClosestNr() function to get the cardinal direction (Est, Nord-Est, etc.) from a dynamic value in degrees.
<?php
// Here add the getClosestNr() function

// array with degrees and cardinal direction
$direction = array(0=>'East',30=>'East-East North',45=>'Northeast',60=>'North-North-East',90=>'North',120=>'Northwest North',135=>'Northwest',150=>'Wes-North West',180=>'West',210=>'West Southwest',225=>'Southwest',240=>'South Southwest',270=>'South',300=>'South-South-East',315=>'Southeast',330=>'Southeast East');

$degrees = array_keys($direction);      // get the degrees into an array

// some degrees of the direction
$deg1 = 0;
$deg2 = 50;
$deg3 = 220;

// get cardinal direction for each degree
$dtn1 = $direction[getClosestNr($degrees, $deg1)];
$dtn2 = $direction[getClosestNr($degrees, $deg2)];
$dtn3 = $direction[getClosestNr($degrees, $deg3)];

// test
echo "$deg1 degrees = $dtn1";       // 0 degrees = East
echo "$deg2 degrees = $dtn2";       // 50 degrees = Northeast
echo "$deg3 degrees = $dtn3";       // 220 degrees = Southwest
?>

0 comments:

Post a Comment