I'm trying to break a PHP array into 3 columns (has to be columns, not rows) so it would look something like this:
Item 1 Item 2 Item 3
Item 4 Item 5 Item 6
Item 7 Item 8 Item 9
Item 10................
The best approach I can think of would be to break the main array into 3 arrays, 1 for each column although I can't work out the best approach to do this - more specifically the criteria I could use to generate the 3 arrays.
Using array_chunk you can split array :
There you go, it just outputs another row when you get to your column count. You might need to add some logic when the data isnt a multiple of 3.
I would use this:
Or when using html table:
When considering your question topic it's first impression is"Column" and I think you needed to focus on visual aspects. "How to display your array as three columns" May be my idea is wrong. But I think you wanted that. Just check following example if my thought is correct.
You can use
array_slice
to extract a section of an array, so:Edit: As @deceze points out, this does the same thing as
array_chunk
. (I knew PHP would have something built-in.) So use that instead!Having just thought about it, this should achieve what I want - whether it's the fastest method though, I'm not sure:
EDIT: The same as above although using a single foreach loop: