Search code examples
phparrayspagination

PHP - Not getting the element I expect from an array


I am paging through the elements of an array. I get the total number of elements in the array with:

$total = count($myarray);

My paging function loads the current element on the page and provides "Previous" and "Next" links that have urls like:

http://myapp.com?page=34

If you click the link I grab that and load it onto the page by getting (I sanitize the $_GET, this is just for example):

$element = $myarray[$_GET['page']];

This should grab the element of the array with a key == $_GET['page'] and it does. However, the problem is that my total count of elements doesn't match some keys because while there are 100 elements in the array, certain numbers are missing so the 100th item actually has a key of 102.

How should I be doing this? Do I need to rewrite the keys to match the available number of elements? Some other method? Thanks for your input.


Solution

  • If you have gaps in the indices, you should reindex the array. You can do that before you generate the links, or probably easier on the receiving page:

    $myarray = array_values($myarray);
    $element = $myarray[$_GET['page']];
    

    This would give you the 100th element, even if it previously had the key 102. (You could use a temporary array of course, if you need to retain the original indexing.)