Page 1 of 1

Loop Explode

Posted: Thu Aug 30, 2007 11:07 pm
by iknownothing
Hey Guys

I have the following code:

Code: Select all

list($quantity, $product, $price) = explode(",", $theorder)
What it does is split up a string into the above list. How can I write it so, if a string contains:

Code: Select all

1,Product1,2.50,4,Product2,4.50
It will explode chunks of 3 into the above variables, print out some HTML (maybe a while or foreach?), and then do it again with the second chunk of 3 and so on..? Everytime I try something similar to what I'm after, I get a white screen...

Posted: Thu Aug 30, 2007 11:17 pm
by John Cartwright
Instead of using list simply explode the string, ie.

Code: Select all

$explode = explode(',', $theorder);
then you can apply array_chunk() on your array to divide it into chunks, ie,

Code: Select all

$chunk = array_chunk($explode, 3);
then loop your chunk normally using foreach()

Posted: Thu Aug 30, 2007 11:33 pm
by iknownothing
Thanks. Am I at all able to add variables names to the three sections of the chunk, like a list, so I can echo them in different places?

Posted: Thu Aug 30, 2007 11:40 pm
by John Cartwright
if you loop $chunk, each loop iteration will contain 3 array elements..

Do a print_r() of $chunk to see how it is laid out.

On second thought, you'll need to pass a third parameter to array_chunk($explode, 3, true) so each chunk array keys will be reindexed so you can still access them as the indexes 0, 1, 2.

Edit | Nevermind about the third parameter, the default behavior will actually reindex.

Posted: Thu Aug 30, 2007 11:51 pm
by iknownothing
Thanks for all your help, works quite nicely now.