Array rotate

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Pineriver
Forum Commoner
Posts: 50
Joined: Fri Aug 15, 2003 5:24 pm

Array rotate

Post by Pineriver »

Hi, I want to be able to display a value from an array in order not random.

$notes = array ("Note1" ,"Note2" ,"Note3" ,"Note4");

Then whenever a visitor goes to that page (or refreshes it) they should see
every time Note1, then Note2, then Note3, then Note4.
How could this be done?
Thanks
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

Code: Select all

foreach($notes as $order){ echo $order.'<br>'; }
Pineriver
Forum Commoner
Posts: 50
Joined: Fri Aug 15, 2003 5:24 pm

Not quite what I am looking for...

Post by Pineriver »

Thats all very well and good if you are looking to print all of the values at once, but I want to pick a single value from an array every time the page loads without being random.

So if I where to load the page it would print "Note1", then refresh right after that it would print "Note2" then "Note3" and so on in rotation.
Thank you for your reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

so you want it to change on a refresh? i would do somtin like this then

Code: Select all

session_start();
if ($_SESSION['note'])
{
$_SESSION['note'] = $num;
echo $notes[$num];
$_SESSION['note'] = $num+1;
}
else
{
echo $notes[0];
$_SESSION['note'] = 1;
}
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

session_start();
$_SESSION['note']++;

$notes = array ("Note1" ,"Note2" ,"Note3" ,"Note4"); 

if ($_SESSION['note'] > 3)
    $_SESSION['note'] = 0;

echo $notes["{$_SESSION['note']}"];
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

to add a little to jcarts superior version of code if you have more than 4 values in your array you can do

Code: Select all

session_start();
$_SESSION['note']++;
 
$notes = array (1 =>"Note1" ,"Note2" ,"Note3" ,"Note4", "Note5", "Note6"); 
 
if ($_SESSION['note'] > count($notes))
    $_SESSION['note'] = 1;
 
echo $notes["{$_SESSION['note']}"];
Post Reply