I have custom code where I get nearest user from array by array key:
$users = [ "4" => "John", "7" => "Alex", "13" => "Smith", "95" => "Taylor" ]; $id = 9; $nearestUserByIdInReverseOrder = false; foreach($users as $userId => $name) { if($id >= $userId) { $nearestUserByIdInReverseOrder = $name; } } echo $nearestUserByIdInReverseOrder;
When I change var $id
to 3 or smaller number then don’t get result. How to get first element of array when $id
smaller then it. And can be shorted or optimized code if I’ve incorrect logic operation in my code? Maybe this possible without looping.
Here is demo
Advertisement
Answer
If you want to get the first value in your array if $id
is less than any of the array keys, you can initialise $nearestUserByIdInReverseOrder
to the first element in the array using reset
:
$users = [ "4" => "John", "7" => "Alex", "13" => "Smith", "95" => "Taylor" ]; $id = 3; $nearestUserByIdInReverseOrder = reset($users); foreach($users as $userId => $name) { if($id >= $userId) { $nearestUserByIdInReverseOrder = $name; } } echo $nearestUserByIdInReverseOrder;
Output:
John
Note that for this (or your original code) to work, the keys must be in increasing numerical order. If they might not be, ksort
the array first:
ksort($users);