Search code examples
phparrayskey

Find and use next and previous value in an dynamic array


I'm trying to get the previous and next value in an dynamic array so I can set those values on my links to the next and previous page. I get the dynamic array from my database and returns the ID's of the category I'm in right now.

As an example, I'm on page ID 6 with category Food than the array is filled with the ID's of other pages with the category Food.

My array works and returns the right values but when I try to get the previous and next ID from my current ID, it returns nothing.

Here is the code with how I fill my array and the var_dump of the array and how I try to get the previous and next value.

$results = array();
while($row = mysql_fetch_array($result)){
    $results[$row[0]] = $row[0]; 
}

array(3) {
[1]=> string(1) "1"
[4]=> string(1) "4"
[6]=> string(1) "6"
}

$index = array_search($id, $results);
if($index !== FALSE){
    $prev = $results[$index + 1];
    $next = $results[$index - 1];
}

The variables $next and $prev return nothing but when I check $results[$index] it return the right ID from the current page. I really can't see anymore what is going wrong.


Solution

  • How about such code?

    $results = array();
    while($row = mysql_fetch_array($result)){
        $results[] = $row[0]; 
    }
    
    $index = array_search($id, $results);
    if ($index !== FALSE){
        $prev = $results[$index + 1];
        $next = $results[$index - 1];
    }
    

    The problem you have is: 4 - 1 != 1 and 4 + 1 != 6

    That's why you get NULLs and notices (or you get notices and do not see them).