Link to home
Start Free TrialLog in
Avatar of johnsonallstars
johnsonallstars

asked on

PHP next and previous options for an array

Hello,

I am working on a new test page using an array containing strings.  I'd like to show each string in the array one at a time and move through them with a previous and back button/link on the test page.

Data:
$myArray = Array(
"bat",
"cat",
"hat",
"ran",
"rat",
"sat"
);

Page-Results:

<< prev.   My favorite word is <b>cat</b>   next >>

//on click-next..$myArray… My favorite word is <b>hat</b> …


At the moment, I am thinking doing a count 0,1,2,3, etc.  If the number is greater than 0, I could use prev. to go backwards.  I am new to php, so seeing what options exist.  It's probably best to use a database for this, but I am just using a hardcoded array at the moment.

Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of johnsonallstars
johnsonallstars

ASKER

Pagination worked for me straight-out the box.  I'll have to look at it more for a better understanding and might be time to incorporate mySQL.

Also, I took a glance at the sessions article. I'll have to work out a few examples to see what works best here.

Good articles.  All very useful and works for me.   Thank you.
If you wanted to do something like pagination with the array, this might be a good starting point.
<?php // demo/temp_johnsonallstars.php

/**
 * http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28677303.html
 */
error_reporting(E_ALL);

// STORE STATEFUL INFORMATION IN THE SESSION
session_start();

// THE TEST DATA ARRAY WILL BE NUMBERED FROM ONE
$data = [ 'x', "bat","cat","hat","ran","rat","sat" ];
unset($data[0]);

// THE START AND END POINTERS
$alpha = 0;
$omega = count($data) + 1;
if (empty($_SESSION['current'])) $_SESSION['current'] = 1;
if (!empty($_GET['curr'])) $_SESSION['current'] = $_GET['curr'];

// GENERATE PREVIOUS LINK NUMBER
$prev = NULL;
if ($_SESSION['current'] > $alpha) $prev = $_SESSION['current'] - 1;

// GENERATE NEXT LINK NUMBER
$next = NULL;
if ($_SESSION['current'] < $omega) $next = $_SESSION['current'] + 1;

// IDENTIFY CURRENT LINK NUMBER
$curr = $_SESSION['current'];

// CONSTRUCT LINKS
$prev_link = NULL;
if ($prev > $alpha)
{
    $prev_link = '<a href="' . $_SERVER['PHP_SELF'] . '?curr=' . $prev . '">Prev</a>';
}

$next_link = NULL;
if ($next < $omega)
{
    $next_link = '<a href="' . $_SERVER['PHP_SELF'] . '?curr=' . $next . '">Next</a>';
}

// CONSTRUCT THE LIST OF LINKS
$links = $prev_link . ' ' . $data[$curr] . ' ' . $next_link;
echo PHP_EOL . $links;

Open in new window

Thanks for the points and thanks for using E-E! ~Ray