Reorder A Numerically Keyed Array Using Array Splice?

/ PHP / by Paul Robinson / 3 Comments
This post was published back on November 12, 2014 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

So today I was given an interesting task by a client. I had the output of a certain function. That function returns an array containing the days of the week (via numeric key, 0 = Sunday, 1 = Monday, etc). The value of each key was an array containing data. Something like this:

Using shorthand array syntax here & just using [] to represent the object of data each array item contained. Oh and as you may have noticed, while a day was never repeated (it only ever contained 7 items) they were never in the correct order. Also note I didn’t have access to the MySQL query to reorder the data as it came in.

To keep things easy to understand they wanted to list out the data grouped by day and list the days from Today onward. So if today was Wednesday (which it is), it would look like:

  • Wednesday
  • Thursday
  • Friday
  • Saturday
  • Sunday
  • Monday
  • Tuesday

Then tomorrow Thursday would be at the top & Wednesday would be pushed to the end… Get the idea. So how do you do that? Well that’s a question I asked myself.

I ended using only a small section of code, but I thought it might be interesting to share.

This is what I settled upon and the client is very happy with the results, but I’m curious as to if there are any easier or more compact ways to do this. The important things were that all the array data is left intact, the array keys are preserved and that it be in the order shown but change each day automatically.

Let me know how you would have done it, I’d love to see how many lines it can be brought down to.

Also don’t forget to visit my new personal blog to keep up-to-date with when new tutorials are incoming and other quirky things from the daily thoughts of a crazy person web developer.


Author’s gravatar


Author’s gravatar author

Hi Salih,

The third part will be coming very soon. I’ll try to get it posted in the next few days (probably the weekend).

Older Comments
Newer Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more