<?php function getClosestIdByAmount($amount = 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 ) ); $result_id = null; $take_next = false; foreach ($prices as $i => $item) { // amount < any price of the array if ($i === 0 && $item['price'] > $amount){ $result_id = $item['id']; break; } else { if ($item['price'] < $amount) { // amount > price1 AND amount < price2 $take_next = true; } elseif ($item['price'] == $amount){ // amount == some price $result_id = $item['id']; break; } else { if ($take_next){ $result_id = $item['id']; } break; } } } return "Amount: " . $amount . " Closest ID: " . $result_id . PHP_EOL; } $amount = 99; echo getClosestIdByAmount($amount); $amount = 113; echo getClosestIdByAmount($amount); $amount = 115; echo getClosestIdByAmount($amount); $amount = 131; echo getClosestIdByAmount($amount);
You have javascript disabled. You will not be able to edit any code.
Value for `_results` contains invalid data `array`