I’m trying to find the highest key of a PHP array, based on another value.
$values = array(0,0,50,100,200,400,800);
If I let’s say I have the value of 125, it should return 3. And it should return 5 if I have any value between 400 and 799.
$output = -1;
$input = 436;
$length = count($values);
for($i=1;$i<=$length;$i++){
if($values[$i]<=$input) { $output++; }
}
// Returns 5
I can loop through the array, but there is 100 values, and that can slow the page down a lot because it is used ~20 times per page load per user. Is there a special function I’m missing? Or am I going to have to foreach the array?
The array is always in order and never changes.
You may be able to do this using array_flip().
How does this work?
Let’s break it down.
$n=0;Our number.$a=array(0,0,50,100,200,400,800);Our array.$a[]=$n;We add our number to the array…sort($a);Sort the thing to place our number in the correct position…$f=array_flip($a);Then we exchange values with indices,print $f[$n]-1And return the value (formerly the index) of the item before the one we added.There may be confusion if $a contains multiple entries of the same number, for example
0in your example. If this happens, you may need to adjust your adjustment (-1in my example) because an index can only appear once in an array. (For example, if0appeared three times, you’d need to adjust your result with-2. This adjustment could be added with extra code, but I’m sure you can figure that part out yourself. 🙂This avoids the loop, but be careful if
$n=0.