2

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;

?>
2
  • Are you sure that your key for array will be remain same like 1,2,3... Commented Sep 22, 2015 at 12:05
  • Isn't it possible to simply do $array[$current_index + 1]? Commented Sep 22, 2015 at 12:08

4 Answers 4

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@BasvanStein: It is way more elegant than your solution and the efficiency difference must be close to 1/infinite. Anyway, check it now, you'll find it hyper-efficient.
0

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.