Kevin Jung
Kevin Jung

Reputation: 3103

PHP explode and changing variables

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!

Upvotes: 1

Views: 445

Answers (3)

UltraInstinct
UltraInstinct

Reputation: 44424

<?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";
?>

Upvotes: 0

satnhak
satnhak

Reputation: 9861

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";

Upvotes: 0

halfdan
halfdan

Reputation: 34204

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.

Upvotes: 1

Related Questions