简体   繁体   中英

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;

?>

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

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");

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.

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

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