PHP get previous array element knowing current array key

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.

Leave a Comment