Good morning from Itlay,
I have a problem with an array and creating a function to check if a value is in a range between two values of array elements, and then (if so) return the key of the first one (and saving in a $var).
On the one hand, the array will have this structure:
array (
RED => 10;
YELLOW => 50;
GREEN => 80;
BLACK => 110;
...
)
And on the other hand, I will have a foreach loop where I need to check each time if a value is in the range where: (i) the minimum is the value of the array element; and (ii) the maximum is the value of the next element. So run among all the array items and then, when it is in the range, setting a $variable with the key of the array element.
CLARIFYING:
Let's take an example with a value of 55 in the foreach loop. The function must:
- first check if 55 is between the first and second element (and so between [RED]=10 and [YELOW]=50);
- then - the answer being no - check if 55 is between the second and third element (and so between [YELLOW]=50 and [GREEN]=80); and so on...
- then - when the answer is yes - setting the variable $var equal to the key of the first item of the correct comparison (and so: $var = YELLOW).
EDIT 1
Thanks to Mick, I have developed the following function. Still does not work.
<?php
function keybetween($array, $number) {
$b = 0;
foreach ($array as $a) {
if ($number> $a && $number < $b){
return $a; // How I can return the key instead of the value?
break;
}else{
$b = $a;
}
}
return end($array); // or return NULL;
}
?>
Do you see any error? And how can I return the key instead of the value?