phpif-statementclosest

PHP Need a function to get closest number out of a object


I have the following code

function closestdown($array, $number) {

                                  sort($array);
                                    foreach ($array as $a) {
                                        if ($a->stappen <= $number){
                                            return $a;
                                    }}
                                    return end($array); // or return NULL;
                                }

and i call it like this:

$citylist = $manager->getStedenList();            
$stappeng = $user->user_stappen;    
$lowernumber = closestdown($citylist, $currentcity);

but instead of giving me the closest number it returns the first lower number it encounters.

example: if i'd use these numbers

$lowernumber = closestdown(1 5 6 99 487 98785, 100);

it returns : 1 while it should return 99.

$citylist looks like :

array(4) {
  [0]=>
  object(Steden)#272 (3) {
    ["name"]=>
    string(10) "Bourguette"
    ["id"]=>
    string(1) "6"
    ["stappen"]=>
    string(2) "13"
  }
  [1]=>
  object(Steden)#268 (3) {
    ["name"]=>
    string(4) "Gent"
    ["id"]=>
    string(1) "4"
    ["stappen"]=>
    string(3) "666"
  }
  [2]=>
  object(Steden)#271 (3) {
    ["name"]=>
    string(16) "garabier(Afrika)"
    ["id"]=>
    string(1) "8"
    ["stappen"]=>
    string(9) "909814037"
  }
  [3]=>
  object(Steden)#297 (3) {
    ["name"]=>
    string(9) "Terneuzen"
    ["id"]=>
    string(1) "7"
    ["stappen"]=>
    string(10) "2147483647"
  }
}

How do i get the closest number to $stappeng (it contains only 1 value example: '100')

Thanks in advance


Solution

  • You need to change something in loop

    <?php
        function closestdown($array, $number) {
          if(count($array)==1){
            return $array[0];
          }
          sort($array);
            foreach ($array as $a) {
                if ($a > $number){//You can use $a->stappen 
                    if(($a-$number)<($number-$previous))
                      return $a;
                    else
                      return $previous;
                }else{
                  $previous = $a;
                }                                        
            }
            return end($array); // or return NULL;
        }
        echo $lowernumber = closestdown([1, 5, 6, 99, 487, 98785], 100);
    ?>
    

    Check demo : https://eval.in/698262