Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting to the next key in an array

Tags:

php

Let's assume I know that there is key "twoVal", but I do not know what is after it. How do I get to the next key for that matter? Shoud I know the position of key "twoVal"? Or there is another way around?

$arr = array('Cool Viski' => array('oneVal' => '169304',
                                   'twoVal' => '166678',
                                   'threeVal' => '45134'));
like image 779
djSk Avatar asked Mar 10 '10 02:03

djSk


People also ask

How to get next array key in PHP?

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

What is a key in an array?

key is just a variable that holds an array index. This example: var key = 7; var item = array[key]; gets you the same value as this: var item = array[7];

What is key in PHP?

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null .


2 Answers

$keys = array_keys($arr['Cool Viski']);
$position = array_search('twoVal', $keys);
if (isset($keys[$position + 1])) {
    $keyAfterTwoVal = $keys[$position + 1];
}
like image 90
deceze Avatar answered Sep 22 '22 14:09

deceze


$arr = array('Cool Viski' => array('oneVal' => '169304',
                                   'twoVal' => '166678',
                                   'threeVal' => '45134'));
foreach($arr as $s=>$v){
    foreach($v as $val){
        if(key($v) == "twoVal"){
            $t=next($v);
            print "next key: ".key($v)."\n";
            print "next key value is: ".$t."\n";;
        }else{
            next($v);
        }
    }
}
like image 32
ghostdog74 Avatar answered Sep 18 '22 14:09

ghostdog74