PHP get previous array element knowing current array key

前端 未结 9 818
心在旅途
心在旅途 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:51

    Just iterate over the array

    $_index = null;
    foreach($myarray as $index => $value)
    {
        if($key == $my_index) // if($key == 550)
        {
            break;
        }
        $_index = $index;
    }
    
    echo $_index; //the prev key from 550;
    

    An alternative solution is to get the keys of your array within an enumerated array like so:

    $keys = array_keys($my_array);
    

    as the keys array is index you can move the the previous key like so:

    $required_key = (array_search(550,$keys,true) - 1);
    

    this will fine the value of 550, and return its index within the keys, remove one to get the previous index

    key we have our previous key to get the value from the original array

    $value = $my_array[$required_key];
    

提交回复
热议问题