1

So I am trying to create a next and previous buttons on my website and I thought I approach it in a rather generic way. I named each of my pages like this:

1.php 2.php 3.php

and so on

So figuratively speaking, while on 2.php, the previous link would point to 1.php and the next link would point to 3.php.

To automate this process on all pages, I am trying to come up with a simple code to add 1 and minus 1 from the current filename.

So in PHP, I did this:

<?php
$dir = $_SERVER['PHP_SELF'];
$dirchunks = explode("/", $dir);
$current = $dirchunks[3];
?>

$current echos out 2.php, the page I am on, is there anyway to add 1 or minus 1 while keeping the .php intacted with the variable $current? so $current 2.php would change to 3.php and 1.php?

I hope my question wasn't confusing and someone can shed some light on my situation. Thanks for the help!

4
  • Um, $current - 1 and $current + 1? Or am I misunderstanding the question? Commented Apr 16, 2011 at 9:41
  • 1
    $current="1.php";$current=$current+1; $current=$current.'php'; Commented Apr 16, 2011 at 9:44
  • Shakti Singh: "1.php" + 1 == 0 Commented Apr 16, 2011 at 9:45
  • this was quiet simple as $current + 1 produces 2 then I just had to add '.php' at the end of it. Commented Apr 16, 2011 at 9:48

3 Answers 3

1

You should not explode by /. What happens if you move your script to another directory? The file name wont be in the same chunk. Use basename to get the file name from a path.

Sign up to request clarification or add additional context in comments.

Comments

0

Remember that there will a wraparound on the first and last pages, and you should use basename to get the name of the file, passing the extension as an optional argument will strip that off too, leaving just the number of the page:

$totalNumberOfPages = 3;
$pageNumber = basename($_SERVER['PHP_SELF'], "php");
$nextPageNumber = (($pageNumber + 1) % $totalNumberOfPages) + 1;
$previousPageNumber = (($pageNumber - 1) % $totalNumberOfPages) + 1;

$dir = dirname($_SERVER['PHP_SELF']);
$nextPage = $dir . "/" . $nextPageNumber . ".php";
$previousPage = $dir . "/" . $previousPageNumber . ".php";

1 Comment

Thanks for the detailed writeup, after using basename, it was some what obvious. :D
0
<?php
$YOUR_MAX_COUNT = 10;
$cur = basename($_SERVER['PHP_SELF'],".php");
$cur = (int)$cur;
$i=1;
for (; $i<$cur; $i++)
    echo "<a href='$i.php'>$i</a>\n";
echo $i . " ";
$i++;
for (; $i<$YOUR_MAX_COUNT; $i++)
    echo "<a href='$i.php'>$i</a>\n";
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.