Loop Explode

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
iknownothing
Forum Contributor
Posts: 337
Joined: Sun Dec 17, 2006 11:53 pm
Location: Sunshine Coast, Australia

Loop Explode

Post 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...
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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()
User avatar
iknownothing
Forum Contributor
Posts: 337
Joined: Sun Dec 17, 2006 11:53 pm
Location: Sunshine Coast, Australia

Post 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?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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.
User avatar
iknownothing
Forum Contributor
Posts: 337
Joined: Sun Dec 17, 2006 11:53 pm
Location: Sunshine Coast, Australia

Post by iknownothing »

Thanks for all your help, works quite nicely now.
Post Reply