Make Money Online - Money Making Reviews

PHP: How To Rotate An Array

During coding time you often get stuck with small-easy problems that just need 3 mins to solve but being in hurry, you better look to find a faster solution from others, on google :)

I was in a similar situation when I had to rotate an array in PHP, but surpsisingly by googling “php rotate array” i found many similar questions but not many solutions, or very few of them that didn’t do what i wanted. This served as a primary though for me to do this post.

I then came up with a very simple solution that just took me 2 minutes ;) It remembered me a gold rule that “often it’s easier to create yourself than find and modify“.

So we have:
Array ([0] =>monday [1] => tuestday [2] => wednesday [3] => thursday [4] => friday [5] => saturday [6] => sunday )

and we want:
Array ([0] => sunday [1] => saturday [2] => friday [3] => thursday [4] => wednesday [5] => tuestday [6] => monday )

right?

Here is the code to do it:

[php]
<?php

$first = array("monday", "tuestday", "wednesday", "thursday", "friday", "saturday", "sunday");
$second = array();

array_push($second, end($first)); //set the pointer to the last element and add it to the second array

//while we have items, get the previous item and add it to the second array
for($i=0; $i<sizeof($first)-1; $i++){
array_push($second, prev($first));
}

print_r($first); print "<br />";
print_r($second);

?>

[/php]

Hopefully this saved someones time :)

Bookmark this on Digg
Share on reddit
Bookmark this on Delicious
Share on StumbleUpon

About

I'm a web developer, internet marketer and entrepreneur. You can find more about me here and join my business opportunity for you here

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Switch to our mobile site