获取上一个数组键的值[重复]

This question already has an answer here:

So I tried doing this :

$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

var_dump(prev($array["second"]));

Hoping to get 111 but I get NULL. Why?

$array["second"] returns 222. Shouldn't we get 111 when we use PHP's prev() function?

How to get the previous value of an array if it exists using the key?

</div>

Your current value from $array["second"] is not an array and prev takes an array as a parameter.

You have to move the internal pointer of the $array and then get the previous value.

$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
while (key($array) !== "second") next($array);
var_dump(prev($array));

prev function expects an array as an argument but you're passing a string.

$array["second"] evaluates to '222'

In this case, you point directly the previous value, without iterating the array.

$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
$keys = array_flip(array_keys($array));
$values = array_values($array);
var_dump($values[$keys['second']-1]);