i have and amount to compare with the prices in the array and bring one id result.
let say the amount is 113, in this case a need to pick id 31 as result because i have to take the one closer but the biggest one or the exact one in case be like 110 or 115 using php 5.3 to 7.1
$prices = array(
array('id' => '28','price' =>100 ),
array('id' => '29','price' =>105 ),
array('id' => '30','price' =>110 ),
array('id' => '31','price' =>115 ),
array('id' => '32','price' =>120 ),
array('id' => '33','price' =>125 ),
array('id' => '34','price' =>130 )
);
i search on internet i try some array function. i found this article here, but does not meet my need.
text
3
Answers
The easiest way is using the next
foreach loop
:Note: the array must be ordered by amount. If
amount is > 130
, thenresult_id
will be anull
.Demo
Update:
Covered case when
amount is < 100
.Demo
Note that the <=> operator is only available in PHP 7 or higher. It can be replace with:
Well, to get the nearest highest for a given amount:
Just run a loop and check if the current price is greater than or equal to the amount.
Now, check if the difference between current price and amount is less than the previously recorded difference. If yes, update the result, else move ahead for the next value.
Snippet:
Driver code:
Online Demo
Note: This will get the result in
O(n)
time and doesn’t require the data set to be in a sorted state in the first place.