How to set an Arrays internal pointer to a specific position? PHP/XML How to set an Arrays internal pointer to a specific position? PHP/XML arrays arrays

How to set an Arrays internal pointer to a specific position? PHP/XML


If your array is always indexed consistently (eg. 'page1' is always at index '0'), it's fairly simple:

$List = array('page1', 'page2', 'page3', 'page4', 'page5');$CurrentPage = 3; // 'page4'while (key($List) !== $CurrentPage) next($List); // Advance until there's a match

I personally don't rely on automatic indexing because there's always a chance that the automatic index might change. You should consider explicitly defining the keys:

$List = array(    '1' => 'page1',    '2' => 'page2',    '3' => 'page3',);

EDIT: If you want to test the values of the array (instead of the keys), use current():

while (current($List) !== $CurrentPage) next($List);


Using the functions below, you can get the next and previous values of the array.If current value is not valid or it is the last (first - for prev) value in the array, then:

  • the function getNextVal(...) returns the first element value
  • the function getPrevVal(...) returns the last element value

The functions are cyclic.

function getNextVal(&$array, $curr_val){    $next = 0;    reset($array);    do    {        $tmp_val = current($array);        $res = next($array);    } while ( ($tmp_val != $curr_val) && $res );    if( $res )    {        $next = current($array);    }    return $next;}function getPrevVal(&$array, $curr_val){    end($array);    $prev = current($array);    do    {        $tmp_val = current($array);        $res = prev($array);    } while ( ($tmp_val != $curr_val) && $res );    if( $res )    {        $prev = current($array);    }    return $prev;}


Using the functions below, you can get the next and previous KEYs of the array.If current key is not valid or it is the last (first - for prev) key in the array, then:

  • the function getNext(...) returns 0 (the first element key)
  • the function getPrev(...) returns the key of the last array element

The functions are cyclic.

function getNext(&$array, $curr_key){    $next = 0;    reset($array);    do    {        $tmp_key = key($array);        $res = next($array);    } while ( ($tmp_key != $curr_key) && $res );    if( $res )    {        $next = key($array);    }    return $next;}function getPrev(&$array, $curr_key){    end($array);    $prev = key($array);    do    {        $tmp_key = key($array);        $res = prev($array);    } while ( ($tmp_key != $curr_key) && $res );    if( $res )    {        $prev = key($array);    }    return $prev;}