| ||||||
|
How to find the closest of a group of numbers to another number with PHP
Here is a function that could come in handy with number games. More specifically: number games where the winner is the person who has guessed the closest number to an end result. Here is how it works: <?php //First we will call on the function closestnumber. // //The first number inside the function is the outcome number // //The others are an array of suggested numbers from which we will //determine the closest. // //closestnumber(outcome number, array closest); $closest = closestnumber(1204 , array(431,1003, 450, 9, 554, 10003, 239, 237, 400)); //Here are the two results that are returned. // //Closest is the winner, and difference is the winning distance //from the outcome number: echo "Closest: ".$closest['closest']."<br>"; echo "Difference: ".$closest['difference']; //And finally herre is the function itself function closestnumber($number, $candidates) { //First we will determine the difference between each of the numbers for($i = 0; $i != sizeof($candidates); $i++) { $results[$i][0] = abs($candidates[$i] - $number); $results[$i][1] = $i; } //Then sort them sort($results); //Returning the closest number and its difference $end_result['closest'] = $candidates[$results[0][1]]; $end_result['difference'] = $results[0][0]; return $end_result; } ?>
|