简体   繁体   中英

How to get value of next key and value of previous key in an array

If I have this array:

 $arr = array(1, 2, 5, 7); 

And the current value of the entry is 5 , how do I get the previous value of 2 and next value 7 ?

It works if I use the following code:

$i = 0;
foreach($result as $check){ 
    if($check == $this->item->id){
        $next = $result[$i+1];
        $prev = $result[$i-1];
    }
    $i++;
}

I thought at first that the $arr[$i + 1] will give me 6

You can use next(); and prev();

Like this:

current($arr); //Use current to see the current element of your array! So in your example 5
next($arr);    //6
prev($arr);    //5

您可以使用next()prev()移动数组指针

It sounds like you're also asking why $arr[$i + 1] and $arr[$i - 1] return the next and previous elements, rather than adding or subtracting from the value of the array element referenced by the index equal to $i .

Keep in mind that the brackets enclose the array index. If you have an expression within the brackets, the result of the expression is the index; there's no reason why if the expression contains a variable, then that variable alone would be treated as the index and any other operations would be applied after retrieving the value of the array element.

So, if $i is 2, then $arr[$i + 1] gives you the value of the element whose index is equal to $i + 1 , ie the element with index 3, which is 7 . $arr[$i] + 1 would give you 6 (retrieves the element whose index is equal to $i , and adds 1 to its value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM