2

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?

  • From the manual - `prev — Rewind the internal array pointer` If you are not looping over the array then the internal array pointer will be the first occurance in the array – RiggsFolly Feb 12 '19 at 14:36
  • Why don't you just skip out on the key so that the key is the index? e.g. 0, 1, 2 - then if you get the array element as $key => $value you can just subtract the $key by 1 e.g. $array[$key-1] – Keydose Feb 12 '19 at 14:37
  • There is already an answer to this. Please check the existed one [here](https://stackoverflow.com/questions/4792673/php-get-previous-array-element-knowing-current-array-key). – dpapadopoulos Feb 12 '19 at 14:37
  • 1
    @dpap flag it as dupe^^ :) – treyBake Feb 12 '19 at 14:38
  • 1
    @dpap definitely a dup, sorry I haven't found that answer. I accepted your dup request. –  Feb 12 '19 at 14:38
  • @Equgonyka it's ok mate. It is possible not to find what you are looking for. That's why I mentioned it :) – dpapadopoulos Feb 12 '19 at 14:41

3 Answers3

2

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

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

matiit
  • 7,969
  • 5
  • 41
  • 65
  • Oh, that's why it's not working! Thanks for the info. How to get then the previous value using the key of the current one? –  Feb 12 '19 at 14:36
2

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));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

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]);
GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26