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
  • 11,708
  • 7
  • 73
  • 89

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,256
  • 1
  • 12
  • 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,506
  • 6
  • 28
  • 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
  • 26,872
  • 8
  • 62
  • 92
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
  • 11,619
  • 5
  • 84
  • 76