user1150087
user1150087

Reputation:

Print each value of a delimited string as an HTML list item

I have input like this:

$recipe['ingredients'] = '100ml milk, 350ml double cream, 150ml water';

I'm 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 nothing gets printed.

Upvotes: 0

Views: 318

Answers (6)

jidesakin
jidesakin

Reputation: 359

You can do this:

$ingredients = explode(',', $row_rs_recipes['ingredients']);

$list = '<ul>';

foreach ($ingredients as $ingredient) 
{
   $list .= '<li>' . $ingredient . '</li>';
}
$list .= '</ul>';

echo $list;

Upvotes: 0

xdazz
xdazz

Reputation: 160923

if (!empty($recipe['ingredients'])) {
    echo '<ul><li>' . implode('</li><li>', explode(', ', $row_rs_recipes['ingredients'])) . '</li></ul>';
}

Upvotes: 0

Maxime
Maxime

Reputation: 235

The explode method already return an array, so you don't have to transform your variable $ingredientsParts into an array.

Just do:

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

Upvotes: 0

Oyeme
Oyeme

Reputation: 11225

$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
    $li = '<ul>';
    foreach($ingredientsParts as $key=>$value){
         $li.=" <li>$value</li>";
    }
    $li.= '</ul>';

echo $li;

Upvotes: 3

Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

  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>";
}

Upvotes: 1

boobiq
boobiq

Reputation: 3024

this should be enough:

$ingredientsParts = explode(', ', $row_rs_recipes['ingredients']);

foreach ($ingredientsParts as $ingredient)
{ 
    echo "<li>$ingredient</li>";
}

or you can explode it by ',' and use echo '<li>' . trim($ingredient) . '</li>'; to remove whitespace from beginning/end of that string

Upvotes: 2

Related Questions