tags:

views:

1683

answers:

2

Im trying to build a little site using XML instead of a database.

I would like to build a next and prev button which will work relative to the content I have displayed.

I found the php function next() and prev() as well as current() but I do not know how to set the pointer to a specific position to be able to navigate relative to the current page.

$list=array('page1','page2','page3')

eg if im displaying contents of page2 how could I tell php i am at $list[1] so that next($list) shows page3?

Thanks in advance

+3  A: 

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);
sirlancelot
Unfortunately there isn't a pointer manipulator function to which you can pass an index. next, current, reset, end, etc, that's all you have. The above is the correct solution if you must use PHP's internal pointer and not a plain old array subscript index.
Trey
how would I match based on the value of the array eg page1 instead of the position 1?
chris
ah its in_array
chris
Actually, you will want to use `current()`. in_array is for seeing if a value is in an array. http://php.net/current
sirlancelot
+2  A: 

The internal array pointer is mainly used for looping over an array within one PHP script. I wouldn't recommend using it for moving from page to page.

For that, just keep track of the page number and the page size (number of items per page). Then, when you're loading another page, you can use them to decide which array items to show. For example:

$pageNum = $_GET["pageNum"];
$pageSize = 10;
$startIndex = ($pageNum - 1) * $pageSize;
$endIndex = ($startIndex + $pageSize) - 1;

(or something similar)

JW
sounds cool but i dont understand
chris