Jump to content

split an array into chunks.


fife

Recommended Posts

I have a variable on my page called,    $recipe['ingredients'];

 

inside the var you have for example....

 

100ml milk, 350ml double cream, 150ml water

 

and so on.  Now Im trying to split it up so it looks as follows

 

<ul>
    <li>100ml milk</li>
   <li>350ml double cream</li>
   <li>150ml water</li>
</ul>

 

So far I have the following code.....

 

  $ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
	   	$ingredients = array($ingredientsParts);
	   while (! $ingredients) { echo" <li>$ingredients</li>";}

 

But for some reason it doesnt work and I do not have the exp with explode to fix it.

Link to comment
Share on other sites

1. When you explode() a string it is automatically converted into an array. You do not need to convert it to an array type as you did on the second line.

 

2. You want to use a foreach() loop to iterate through an array, not a while loop.

 

$ingredientsAry = explode(',', $row_rs_recipes['ingredients']);
foreach($ingredientsAry as $ingredient)
{
    echo "<li>$ingredient</li>";
}

 

 

In fact you can just do a foreach() loop on the explode() value

foreach(explode(',', $row_rs_recipes['ingredients']) as $ingredient)
{
    echo "<li>$ingredient</li>";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.