PHP array_chunk()

Thursday, May 9th, 2013

I recently came across a problem while trying to arrange links in a footer menu, to all countries of the world. The list of links to the countries had to be in column format to avoid looking ugly and making the page unreasonably long. Sure you could just make a list of countries, say 100, and split them into 5 columns of 20 countries, easy right! But what if the number of countries changes, which has been known on many occasions, how can you make it responsive?

Fortunately PHP has a ready made solution to the problem which is array_chunk(). The PHP manual has a pretty good explanation as to how it all works, and I would advise you to read it, rather than me trying to explain it all here. But basically it returns a multidimensional numerically indexed array, starting with zero, and effectively splits an array into chunks. The parameters accept an array to work on, and the size of the chunks, or number of columns in our case. What it doesn’t tell you however is how to use it in a way that I think many developers would like to, which is for a dynamic or responsive menu that has a fixed number of columns.

The following example will hopefully show you how easy this is using array_chunk(). I have used a hard coded array in the example but this is just for convenience. You should get the list from your database using a MySQL query and populate from there. I’ve also added some inline CSS but again this was just for convenience so you can see what is happening.

Also you will need to insert the relative href link within the <a> tags to create the links. For example you could try creating a folder with a html page for each country in your list and link to it in the following way,

or however you choose. I’ve left the href blank in the following code but you can try the above method if you want.

There you go a simple way to create a dynamic menu with a fixed number of columns. It should come out looking like this:

 

Tags: , ,

2 comments on "PHP array_chunk()"

  1. Pingback: Stephen
  2. Pingback: jesse

Comments are closed.