phparrays

php Find if array value is bigger then a variable


Hello a am trying to create a function that will return me a value from the array if the value is bigger the a variable. the array is

[0] => Array ( [payment] => 1 [amount] => 100) 
[1] => Array ( [payment] => 2 [amount] => 300 ) 
[2] => Array ( [payment] => 3 [amount] => 800 )

$variable = 350;

I need to get the payment value if is bigger then 300 amount . what I mean is to get back the value payment = 2. that is bigger then 300 and smaller the 800.

Thanks


Solution

  • As you said that if you are searching fr 350 it need to return record of amount 300, that means:-

    You are searching for nearest amount first and then get payment value of that corresponding amount

    Do like below:-

    <?php
    
    
    $array = Array(
                '0' => Array ( 'payment' => 1, 'amount' => 100) ,
                '1' => Array ( 'payment' => 2, 'amount' => 300 ) ,
                '2' => Array ( 'payment' => 3, 'amount' => 800 )
            );
            
    function getNearest($search, $arr) {
       $closest = null;
       foreach ($arr as $item) {
          if ($closest === null || abs($search - $closest) > abs($item - $search)) {
             $closest = $item;
          }
       }
       return $closest;
    }
    
    $key = array_search(getNearest(350, array_column($array,'amount')),array_column($array,'amount'));
    
    echo $array[$key]['payment'];
    

    Output: https://3v4l.org/spN2q