gogol75 gogol75 - 14 days ago 6
PHP Question

PHP, generate previous and next links from array with numbers

I have an array like this:

$pages = (1, 29, 209, 389, 440, 527)


And I want to make simple HTML navigation through these pages. Only 'first', 'last', 'prev' and 'next' links.
And when I click the 'next'/'prev' link they had to change accordingly.
E.g. when I am at page 389 prev and next to be 209 and 440. If I am at page 440 prev and next to be 389 and 527.

Answer

Here is one simple approach:

$pages = array(1, 29, 209, 389, 440, 527);
$current = isset($_GET['page']) ? $_GET['page'] : $pages[0];

// current page
$key = array_search($current, $pages);
echo 'current page: ' . $pages[$key] . '<br />';

// previous page
$prev = $key - 1;
if ($prev >= 0 && $prev < count($pages)) {
    echo '<a href="?page=' . $pages[$prev] . '">prev</a> | ';
} else {
    echo 'prev | ';
}

// next page
$next = $key + 1;
if ($next >= 0 && $next < count($pages)) {
    echo '<a href="?page=' . $pages[$next] . '">next</a>';
} else {
    echo 'next';
}

Assuming the keys will always be in order, then the first page will always be at $pages[0], and to get the last you could use $pages[key(array_slice($pages, -1, 1, true))]

Comments