Maybe I'm wrong but from the first part of your question I think you don't need to get the previous or the next key/item of the array.
I want to create if conditions in the type of
if (($variable >=2) && ($variable <3)) { echo '10'; }
It seems you have some intervals and you want to know what interval contains the value of $variable
and print a different value for each interval.
The easiest solution for this is to use a set of cascaded if
statements:
if ($variable < 2) { // $variable < 2
echo('N/A');
} elseif ($variable < 3) { // 2 <= $variable < 3
echo(10);
} elseif ($variable < 4) { // 3 <= $variable < 4
echo(14);
} elseif ($variable < 5) { // 4 <= $variable < 5
echo(15);
} elseif ($variable < 8) { // 5 <= $variable < 8
echo(16);
} elseif ($variable < 14) { // 8 <= $variable < 14
echo(17);
} elseif ($variable < 51) { // 14 <= $variable < 51
echo(18);
} elseif ($variable < 94) { // 51 <= $variable < 94
echo(19);
} else { // 94 <= $variable
echo(20);
}
This strategy works fine and it is easy to read and understand.
However, it doesn't work when the list of ranges (and their values) is not known when the code is written (it is loaded from the database, for example).
In such a situation, a simple foreach
loop can be used to iterate over the list an identify the correct range.
function getValue($input)
{
$limits = array(
2 => 10,
3 => 14,
4 => 15,
5 => 16,
8 => 17,
14 => 18,
51 => 19,
94 => 20,
);
foreach (array_reverse($limits, TRUE) as $key => $value) {
if ($key <= $input) {
return $value;
}
}
return 'N/A';
}
echo(getValue(2)); # 10
echo(getValue(6)); # 16
echo(getValue(25)); # 18
echo(getValue(51)); # 19
echo(getValue(100)); # 20
The function array_reverse()
returns an array with elements in the reverse order. Passing TRUE
as its second argument makes it preserve the key/value association of the original array.
The foreach
loop compares the input value with the keys of the array in reverse order. When a key that is smaller than the input value is found, it is the lower range bound and the associated value is returned.
If the input value is smaller than any key of the array then it means $variable < 2
and it returns N/A
because this case is not described in the question.
If you need to run this code many times and/or the list of ranges is large then it's better to have the list of bounds sorted descending and remove the call to array_reverse()
(use just $bounds
instead).