# array_keys using a conditional

I’m a bit stuck on this one, I know I can do it with a loop but was wondering if there was a more elegant way.

``````
\$arr = array(2,5,6,9,12);
\$value = 7;

echo array_keys(\$arr, conditional here ));

//Example conditional
if(\$value < \$arr_value)

``````

I basically want to find the key of the largest amount in the array that is lower than my value amount. So in this case 2 (which has a value of 6, the largest amount lower than 7).

If I could return an array with the keys of all lower values I could take the max value from that.

you can’t take max value from the array of keys

what is estimated size of this array? and where it come from and what is whole task in less abstract terms, if you please?

It’s for a store, to work out discount amounts.

I’ll have two arrays of qualifying and discount amounts, both have exactly the same amount of values, probably around 4 or 5, all numeric.

I then want to check the current order amount to find the tier (i.e. the key) from the qualifying amounts array, and get the correct discount from the discount amounts array.

Thanks

I guess a loop will do

``````
for(\$i = 0;\$i < count(\$arr);\$i++)
{
if(\$value < \$arr[\$i])
{
break;
}
\$max_under_value_key = \$i;
}
``````

How often would you estimate that there is an exact match?

``````
\$arr = array(2,5,7,9,12);
\$value = 7;

``````

Not really anymore elegant, however, if you introduce an object to handle the filtering based on DiscountStrategies etc, much more powerful.

``````
\$array = range(0, 9);

print_r(
array_filter(
\$array,
create_function(
'\$value',
'return \$value > 6;'
)
)
);

/*
Array
(
 => 7
 => 8
 => 9
)
*/

``````

Good solution Anthony.Even if we put the random array values, still it works.

``````\$array = array(3,5,8,1,3,4,6,3,9);

``````

Very usefully.

Thank you. ``````
echo \$key = array_search(max(array_filter(\$arr, function(\$val) use (\$value) {
return \$val < \$value;
})), \$arr, true);

``````

I’d just use a loop though…