Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get previous array element knowing current array key

Tags:

arrays

php

I have an array with specific keys:

array(     420 => array(...),      430 => array(...),      555 => array(...) ) 

In my application I know current key (for example 555). And I want to get the previous array element. In this example it is array element with key 430. How can I do this in PHP? I tried to work with prev(), but for this function we should know current array element. I didn't find function, what set the current array element.

like image 612
Alex Pliutau Avatar asked Jan 25 '11 11:01

Alex Pliutau


2 Answers

One option:

To set the internal pointer to a certain position, you have to forward it (using key and next, maybe do a reset before to make sure you start from the beginning of the array):

while(key($array) !== $key) next($array); 

Then you can use prev():

$prev_val = prev($array); // and to get the key $prev_key = key($array); 

Depending on what you are going to do with the array afterwards, you might want to reset the internal pointer.

If the key does not exist in the array, you have an infinite loop, but this could be solved with:

 while(key($array) !== null && key($array) !== $key) 

of course prev would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.

like image 61
Felix Kling Avatar answered Sep 21 '22 05:09

Felix Kling


Solution with fast lookups: (if you have to do this more than once)

$keys = array_flip(array_keys($array)); $values = array_values($array); return $values[$keys[555]-1]; 

array_flip(array_keys($array)); will return an array mapping keys to their position in the original array, e.g. array(420 => 0, 430 => 1, 555 => 2).

And array_values() returns an array mapping positions to values, e.g. array(0 => /* value of $array[420] */, ...).

So $values[$keys[555]-1] effectively returns the previous elements, given that the current one has key 555.

Alternative solution:

$keys = array_keys($array); return $array[$keys[array_search(555, $keys)-1]]; 
like image 32
Arnaud Le Blanc Avatar answered Sep 21 '22 05:09

Arnaud Le Blanc