Page 1 of 1

Arrays: Get the previous key.

Posted: Mon Nov 13, 2006 6:59 am
by bokehman
Arrays: Get the previous key.

Code: Select all

$myArray = array(10 => 'something', 20 => 'something else');
Is there any way, preferably without loops, that I can feed in a number, for example 15, and the array will return the value of the first key that is equal to or less than 15?

Posted: Mon Nov 13, 2006 7:29 am
by Jenk
This is a bit long winded, perhaps someone else knows a simpler solution, or perhaps looping is a better way:

Code: Select all

<?php

function findPrevious($array, $value)
{
    $values = array_values($array);
    return $values[array_search($value, $values) -1];
}

echo findPrevious(array(10=>1, 20=>2), 2);

?>
or if you want the key:

Code: Select all

<?php

function findPreviousKey($array, $value)
{
    $values = array_values($array);
    $keys = array_keys($array);
    return $keys[array_search($value, $values) -1];
}

echo findPreviousKey(array(10=>1, 20=>2), 2);

?>

Posted: Mon Nov 13, 2006 7:59 am
by bokehman

Code: Select all

echo findPreviousKey(array(10 => 'something', 20 => 'something else'), 15);
That doesn't work!

Posted: Mon Nov 13, 2006 9:42 am
by m3mn0n
That's because I believe it's made to search for exactly what it says, the previous key than the key you entered

So if you have an array like 10, 15, 20... and you enter 15, you need to modify that snippet in order for it to search for anything below 15 instead of 14 like it does now.

Posted: Mon Nov 13, 2006 10:29 am
by bokehman
m3mn0n wrote:That's because I believe it's made to search for exactly what it says, the previous key than the key you entered

So if you have an array like 10, 15, 20... and you enter 15, you need to modify that snippet in order for it to search for anything below 15 instead of 14 like it does now.
Which means a loop, doesn't it? Just what I was trying to avoid.

Posted: Mon Nov 13, 2006 11:03 am
by Jenk
You can only search for existing keys, and as 15 doesn't exist in a 10 step array, it won't find it..

Try this:

Code: Select all

<?php

function findKeyLowerThan($array, $value)
{
    return max(
        array_filter(
            array_keys($array),
            create_function('$a', 'return $a < ' . $value . ';')
        )
    );
}

echo findKeyLowerThan(array(10=>1, 20=>2), 15);

?>