3

For example i have an array with the element of following

$array = array(
               1 => "a",
               3 => "c",
               4 => "d",
               6 => "f",
              );

how could i get next key from given key, if I'm using some function like

get_next_key_array($array,1);
it should return 3.

if it be

 get_next_key_array($array,4);
 it should return 6.

Is it can be done, I know that next(),current(),prev() in php, but i don't know how to implement my required result using default functions. Please help me.

0

4 Answers 4

13

Try this out

function get_next_key_array($array,$key){
    $keys = array_keys($array);
    $position = array_search($key, $keys);
    if (isset($keys[$position + 1])) {
        $nextKey = $keys[$position + 1];
    }
    return $nextKey;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This one is still a lifesaver and a keeper. Add '- 1' into a new function and you have all your prev-next-buttons working on every array you can come up with.
A good IDE will inform you that $nextKey might not be declared at the return line. Maybe it should be return $keys[$position + 1] ?? null; instead of the if+return. This answer is missing its educational explanation.
2
function get_next_key_array( $array, $find_key ) {
    $flag = false;
    foreach( $array as $key => $value ) {
        if( $flag ) {
            return $key;
        }
        if( $key === $find_key ) {
            $flag = true;
        }
    }
    return false;
}

1 Comment

This answer is missing its educational explanation.
0

try this:

$len = count($array);
$keys = array_keys($array);
$keys_map = array_flip($keys);
if($keys_map[$current_key]>=$len-1)
    $nextkey = $keys[0];
else
    $nextkey = $keys[$keys_map[$current_key]];

1 Comment

This answer is missing its educational explanation.
0

This is done for normal case:

function get_next_key_array(&$array, $key)
{
    while (key($array) !== $key) {
        next($array);
    }
    next($array);

    return key($array);
}
$array = array(
    1 => 'a',
    3 => 'c',
    4 => 'd',
    6 => 'f',
);
$key = 4;
echo get_next_key_array($array, $key);

DEMO

2 Comments

Note that if the key is not detected, you go in an infinite loop.
This answer is missing its educational explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.