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 ![]()

