Forum Moderators: coopster

Message Too Old, No Replies

find item in array

before the given key

         

WhosAWhata

12:31 am on Aug 15, 2004 (gmt 0)

10+ Year Member



say i have the following array

$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4');

how do i select the value that is provided BEFORE the key i provide

ex:
$mykey = "k2";
$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4');
$value = somefunctions(); // gives the value v1

ex:
$mykey = "k4";
$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4');
$value = somefunctions(); // gives the value v3

this is the last thing i do with the array, so if you have to cut pieces out it, its fine

coopster

1:51 am on Aug 15, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



One way would be to loop through, compare your current, then return the previous:
$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4'); 
$mykey = "k2";
while(list($key, $value) = each($array)) {
if ($key = $mykey) {
print "Previous is: " . prev($array);
break;
}
}

WhosAWhata

5:06 pm on Aug 15, 2004 (gmt 0)

10+ Year Member



thanks, just what i was looking for