Jump to content

Array Shuffling


Adeus

Recommended Posts

Hello, I am trying to accomplish somewhat of a shuffle (for lack of better term). I am using mysql_fetch_array to populate the array. I am trying to get it to act like this;

 

{0, 1, 2}

{1, 2, 0}

{2, 0, 1}

then back to {0, 1, 2}

etc...

 

As you can see, the first item in the array moves to the back with each "shuffle." I have checked out array_shuffle, array_splice, etc... I can't seem to find a good way to do this. Any help is much appreciated.

 

At first, I used a variable which increases by +1 each page load, looping from 0 to 2. I then used this number for the LIMIT ($number, 3) in my SQL query. This worked, but of course did not append the first item to the end of the list after a page load.

Link to comment
Share on other sites

How about this:

 

<?php

$testArray = array(0,1,2);

$times = 5; // This is the number of times you want to perform your rotation.

for($i=0; $i = $times; $i++){
  $tmp = array_shift($testArray); // Take value from the front.
  array_push($tmp);  // Put front value on the back.
}

?>

 

Hope that answers your question.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.