user8056359
user8056359

Reputation: 457

Getting the previous and next keys/values in array from current position (PHP)

I have an array similar to the following:

const BookIndex = array
(
    '1' => 'Chapter 1',
    '1.1' => 'Chapter 1.1',
    '1.1.1' => 'Chapter 1.1.1',
    '2' => 'Chapter 2',
    '2.1' => 'Chapter 2.1',
    '2.1.1' => 'Chapter 2.1.1',
);

Let's say that I have determined somehow that the current key (position) I care about is the '2' key. How do I find the previous and next keys?

$CurrentKey = '2';
$CurrentValue = BookIndex[$CurrentKey];

$PreviousKey = null; // I need to figure out the previous key from the current key.
$PreviousValue = BookIndex[$PreviousKey];

$NextKey = null; // I need to figure out the next key from the current key.
$NextValue = BookIndex[$NextKey];

Upvotes: 0

Views: 3355

Answers (3)

Jigar Shah
Jigar Shah

Reputation: 6223

You can use array functions for that

$NextKey = next($BookIndex); // next key of array

$PreviousKey = prev($BookIndex); // previous key of array

$CurrentKey = current($BookIndex); // current key of array

pointing to specific position

$CurrentKey = '2';

while (key($BookIndex) !== $CurrentKey) next($BookIndex);

Upvotes: 1

Serge Kishiko
Serge Kishiko

Reputation: 486

Just to clarify the previous answer, with the associative arrays, next() and prev() functions return the next or the previous value - not the key - regarding to your question.

Suppose that with your $BookIndex array. If you want to move and get the next value (or the previous), you can do like this:

$nextChapter = next($BookIndex); // The value will be 'Chapter 1.1'
$previousChapter = prev($nextChapter); // The value will be 'Chapter 1'

More, next() and prev() functions expect parameter to be array, not a const.

Upvotes: 0

スージン
スージン

Reputation: 153

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;
    }

    function get_previous_key_array($array,$key){
        $keys = array_keys($array);
        $position = array_search($key, $keys);
        if (isset($keys[$position - 1])) {
            $previousKey = $keys[$position - 1];
        }
        return $previousKey;
    }


    $CurrentKey = '2';
    $CurrentValue = BookIndex[$CurrentKey];

    $PreviousKey = get_previous_key_array($BookIndex,$CurrentKey)
    $PreviousValue = BookIndex[$PreviousKey];

    $NextKey = get_next_key_array($BookIndex,$CurrentKey)
    $NextValue = BookIndex[$NextKey];

Upvotes: 1

Related Questions