0

lets say I've got an

$possibleTaxes = array(7,8,13,23);

and then I've got some values like 13.05, 18, 6.5 etc. I need function that will return given number rounded to closest values from those inside given array so:

roundToValues(19,$possibleTaxes) //returns 23
roundToValues(16,$possibleTaxes) //returns 13

Also additional option to round only to bigger value, even if smaller is closer would be good

Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91

4 Answers4

1

Try this once

function roundToValues($search, $possibleTaxes) {
$closest = null;
foreach($possibleTaxes as $item) {
  if($closest == null || abs($search - $closest) < abs($item - $search)) {
     $closest = $item;
  }
  }
 return $closest;
}
nickle
  • 4,636
  • 1
  • 13
  • 11
0

To round only to bigger value:

<?php
function roundToValues($target, $possibleTaxes)
{
    rsort($possibleTaxes);
    $index = 0;
    foreach ($possibleTaxes as $i => $value)
    {
        if ($value < $target)
        {
            break;
        }
        else
        {
            $index = $i;
        }
    }
    return $possibleTaxes[$index];
}
$possibleTaxes = array(7,8,13,23);
echo roundToValues(19,$possibleTaxes), "\n"; // output 23
echo roundToValues(11,$possibleTaxes), "\n";// output 13
srain
  • 8,944
  • 6
  • 30
  • 42
0

You just have to find the absolute difference between your number and each of the numbers of the array. And then take the number with the smallest difference.

function roundToValues( $tax, array $possibleTaxes ) {
    $differences = array();
    foreach( $possibleTaxes as $possibleTax) {
        $differences[ $possibleTax ] = abs($possibleTax - $tax);
    }
    return array_search(min($differences), $differences);
}

PHPFiddle working example

Teneff
  • 30,564
  • 13
  • 72
  • 103
0
function roundToValues($no,$possibleTaxes){

            array_push($possibleTaxes,$no);  
            sort($possibleTaxes); 
            $x=array_search($no,$possibleTaxes); 
            if(($no-@$possibleTaxes[$x-1]) > (@$possibleTaxes[$x+1]-$no) ){ 
                return @$possibleTaxes[$x+1];
            } else {
                return @$possibleTaxes[$x-1];
            } 



}

$possibleTaxes = array(7,8,13,23);
echo roundToValues(16,$possibleTaxes);
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78