Bruno Landowski
Bruno Landowski

Reputation: 4139

PHP: Get next/prev element of an array with loop if last/first

I don't manage to add a navigation arrow to my portfolio. I would like to get next and prev id based on current id. The issue is when the $current_id is the last of array, I don't know how to go to the first one to create a kind of loop. And the same if the $current_id is the first element, how to have the last element as prev ? I'm stuck, can you please help me ?

Here is my code:

<?php 

    $current_id = "10";

    $array = array(
        "1" => "aa",
        "2" => "bb",
        "3" => "cc",
        "4" => "dd",
        "5" => "ee",
        "6" => "ff",
        "7" => "gg",
        "8" => "hh",
        "9" => "ii",
        "10" => "jj",
    );


    $current_index = array_search($current_id, $array);

    $next = $current_index + 1;
    $prev = $current_index - 1;

?>

Upvotes: 2

Views: 1771

Answers (4)

Rohit Kumar
Rohit Kumar

Reputation: 1958

You could achieve it , if you have last id of page .

Try something as

$last=count($array);
$next = $current_index + 1;
$next=$next<0?$last:$next;
$prev = $current_index - 1;
$prev =$prev==$last?1:$prev

Upvotes: 0

Jinksy
Jinksy

Reputation: 451

You could use reset() and end() functions to move the array pointer to the beginning and the end of the array. So, before processing your array you could do something like:

end($array);
$end = key($array);

and then:

reset ($array);
while (current ($array)) {
    $current_index = key($array);
    $current_value = current($array);
    if ($current_index == $end) 
        reset($array);
    else
        next($array);
}

Or, build some sort of linked list where every element of your array would have a pointer/reference to the next element.

Upvotes: 0

Amarnasan
Amarnasan

Reputation: 15549

Use modulo THIS way:

$current_id = 9;

$array = array(
    "aa",
    "bb",
    "cc",
    "dd",
    "ee",
    "ff",
    "gg",
    "hh",
    "ii",
     "jj",
);

$next = ($current_id+($count=count($array))+1)%$count;
$previous = ($current_id+$count-1)%$count;

print("$previous $next");

Upvotes: 1

Niki van Stein
Niki van Stein

Reputation: 10734

You can use modulo % for that for the next value:

$number_of_elements = count($array);
$next = ($current_index + 1) % $number_of_elements;

And an if for the prev value, since modulo does not like negative numbers

$prev = $current_index - 1
if ($prev < 0){
    $prev = $number_of_elements - 1;
}

Upvotes: 3

Related Questions