PHP get previous array element knowing current array key

前端 未结 9 824
心在旅途
心在旅途 2020-12-01 06:41

I have an array with specific keys:

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

In my applicati

9条回答
  •  半阙折子戏
    2020-12-01 06:48

    If your data is large then it might be a best practice to avoid looping. You could make your own custom function, like so:

    $array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
    
    function previous($key, $array) {
      $keysArray = array_keys($array);
      $keyNumber = array_search($key, $keysArray);
      if ($keyNumber === 0) {
        $keyNumber = count($array);
      }
      return $array[$keysArray[$keyNumber - 1]];
    }
    var_dump(previous("second", $array));
    

    Note that if you provide first key then it will return the last value, like a cyclic array. You can handle it however you like.

    With a bit tweak, you can also generalize it to return next values.

    As for why prev isnt working is because it isnt used for that purpose. It just sets the internal pointer of the array to one behind, exact inverse of next

    I hope it helps

提交回复
热议问题