Page 1 of 1

Creating a next / previous link for easy navigation

Posted: Sun Aug 22, 2010 3:17 am
by caraew
Okay the following code is working to a point :

Code: Select all

<?php
$thumbs = array(
  array(
  "link"  =>"Advanced mouse-over",
  "url"  =>"http://localhost//chouselive-new/demo/css/mouse-over/mouseover-anywhere.php",
  ),
  array(
  "link"  =>"Buttons",
  "url"  =>"http://localhost//chouselive-new/demo/css/buttons/buttons.php",
  ),
  array(
  "link"  =>"Centre page horizontally and vertically",
  "url"  =>"http://localhost//chouselive-new/demo/css/centre/centre.php",
  ),
  array(
  "link"  =>"Read More",
  "url"  =>"http://localhost//chouselive-new/demo/jquery/read-more/read-more.php",
  )
);

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

$currentUrl = curPageURL();

while($array = next($thumbs)) {
  if($array['url'] == $currentUrl) {
     $previous = prev($thumbs);
     next($thumbs);
     $next = next($thumbs);
     break;
  }
}
?>

<a href="<?php echo $previous['url']; ?>" title="<?php echo $previous['link']; ?>">previous demonstration</a><br />
<a href="<?php echo $next['url']; ?>" title="<?php echo $next['link']; ?>">Next demonstration</a>


The idea is that there is a listing #thumbs of urls which link to web pages. The second part of the script determine the current url then the third part of the script takes the current url and lists the next and previous webpage relative to its position in the #thumbs array.

It works fine unless you are on the actual first or last page. if you on the first page it does not return any values for for the next or previous link. If you are on the last page, it on provides a link for the previous page.

While I understand that the last page cannot have a next link, I can not work out while the first page will not even provide a next link.

Ideally I would like to have the first pages previous link to link back to the menu page ../menu.php and the last page next link to do the same.

I also need to fix the glitch that results in the first page next link not linking to the next page in the #thumbs array.

I am a very new beginner to php so please be patient with me :-)

Re: Creating a next / previous link for easy navigation

Posted: Mon Aug 23, 2010 1:33 am
by Gargoyle

Code: Select all

foreach($thumbs as $k=>$v)
{
if($v['url']==$currentUrl)
{
$previous = $k>0?$thumbs[$k-1]:'';
$next = $k<count($thumbs)-1?$thumbs[$k+1]:'';
}
}
you also need to write your HTML links dynamically