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.
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]];
I solved this issue in this way:
function getPrevKey($key, $hash = array()) {
$keys = array_keys($hash);
$found_index = array_search($key, $keys);
if ($found_index === false || $found_index === 0)
return false;
return $keys[$found_index-1];
}
@return previous key or false if no previous key is available
Example:
$myhash = array(
'foo' => 'foovalue',
'goo' => 'goovalue',
'moo' => 'moovalue',
'zoo' => 'zoovalue'
);
echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo