
Originally Posted by
learning_brain
I also have an additional problem. I don't think I can use foreach because I need to specify each row number in incremental order to achieve this.
Though foreach only handles entire arrays, you can combine it with array_slice as you do and you can process a single section of an array just fine.
PHP Code:
foreach (array_slice($items, $startRow, $rowsPerPage) as $i => $item) {
$rowNum = $i+$startRow;
...
}
Note: the name $maxRows is misleading; $rowsPerPage is more accurate. Also, array_slice takes the offset & length of the slice, not start & end. Third, array_slice doesn't preserve indices, though this may not matter for your code.
Of course, there's nothing wrong with using a for loop rather than a foreach loop. Personally, I prefer for in cases like this, as it's readable and the array_slice will use more memory.

Originally Posted by
learning_brain
The pageNum and startRow work a treat but the endRow is always startRow + whatever the rows per page is.....which is wrong. I can't get my head round how to manage this if,say, there are 45 result rows on a page of e.g. 50 loops.
I'm not sure of the problem you're facing. With array_slice, it shouldn't matter if there aren't enough items in the array to produce the requested length; it will simply stop at the end. array_slice(range(0,10), 5, 100); will give you range(5,10). Outside of array_slice, you can use min() to set the upper bound:
PHP Code:
$fromRow = $startPage * $rowsPerPage;
$upto = min($fromRow + $rowsPerPage, count($rows));
for ($i=$fromRow; $i < $upto; ++$i) {
...
}

Originally Posted by
learning_brain
I'm also not sure my totalPages is right... :S
Then test it. In general, figuring out all the important edge cases to test can take some work, but here testing 0, 10, 20 and 30 results at 20 results per page should be sufficient.
Considering your search implementation, you should cache search results so you don't need to re-run the search for every page of results.