Explode to array and print each element as list item - php

I have a set of numbers in a table field in database, the numbers are separated by comma ','.
I am trying to do the following:
Step 1. : SELECT set of numbers from database and explode it to array :
$array = explode(',', $set_of_numbers);
Step 2. : Print each element of the array as list item by using foreach loop :
foreach ($array as $list_item => $set_of_numbers){
echo "<li>";
print_r(array_list_items($set_of_numbers));
echo "</li>";}
Please anybody tell me what is wrong. Thank you.

$numbers = '1,2,3';
$array = explode(',', $numbers);
foreach ($array as $item) {
echo "<li>$item</li>";
}

Assuming your original $set_of_numbers is simply a CSV string, something like 1,2,3,4,..., then your foreach is "mostly" ok. But your variable naming is quite bonkers, and your print-r() call uncesary:
$array = explode(',', $set_of_numbers);
foreach($array as $key => $value) {
echo "<li>$key: $value</li>";
}
Assuming that 1,2,3,4... string, you'd get
<li>0: 1</li>
<li>1: 2</li>
<li>2: 3</li>
etc...

$numbers = "1,2,3";
$array = explode(",", $numbers);
/* count length of array */
$arrlength = count($array);
/* using for while */
$x = 0;
while ($x < $arrlength) {
echo "<li>$array[$x]</li>" . PHP_EOL;
$x++;
}
echo PHP_EOL;
/* using for classic */
for ($x = 0; $x < $arrlength; $x++) {
echo "<li>$array[$x]</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc */
foreach ($array as $value) {
echo "<li>$value</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc key */
foreach ($array as $key => $value) {
echo "<li>$key => $value</li>" . PHP_EOL;
}
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/ZqT4Yi" ></iframe>

You actually don't need to explode on the commas. You can just replace each comma with an ending tag followed by an opening tag and then wrap your whole string in an opening and closing tag.
$set_of_numbers = '1,2,3';
echo '<li>' . str_replace(',', '</li><li>', $set_of_numbers) . '</li>';
// outputs: <li>1</li><li>2</li><li>3</li>
No looping is necessary.

Here is answer for your question to get ride of your problem
$Num = '1,2,3,4,5,';
$Array = explode(',',$Num);
foreach ($Array as $Items)
{
echo "<li>&Items</li>"; // This line put put put in the list.
}

This can easily be achieved by the following code snippet:
<?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
echo '<li>'.$my_number.'</li>';
}
echo '</ul>';
The above code will output the following HTML:
<ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>
Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples

Related

How to remove the last comma from foreach loop?

I am trying to remove the last comma(,) from foreach loop in php with the following code
<?php
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
<?php echo $tag_name; ?> ,
<?php }
?>
Right I am getting result like
Hello, How, sam,
But i wants to remove the last comma
By placing the HTML in a simple string variable and then using rtrim() on the resulting string before outputting it this should remove the final , from the string
<?php
$out = '';
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
// move inside loop and amend to place in a simple string var
$out .= '' . $tag_name . ',';
?>
echo rtrim($out, ',');
You can also use the following code -
<?php
$numItems = count($snippet_tags);
$i = 0;
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
if(++$i === $numItems)
echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a>";
else echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a> ,";
<?php
}
?>

How to split a string every certain character?

Not a php guru here.
I have a string:
works/but/needs/splitting
I'd need the output in a ul list
<ul>
<li>works</ul>
<li>but</li>
<li>needs</li>
<li>splitting</li>
<ul>
I have been looking into explode("/", $text); and tried
$originalstring = "works/but/needs/splitting";
$delimiter = "/";
if(strpos($originalstring,$delimiter) > 0){
But I just don't know much of php and I can't work it out
Sorry I might not understand your questions, But split by / is this
$originalstring = "works/but/needs/splitting";
$pieces = explode("/", $originalstring);
echo '<ul>';
foreach ($pieces as $pi){
echo '<li>'.$pi.'</li>';
}
echo '</ul>';
$originalstring = "works/but/needs/splitting";
$e=explode('/',$originalstring); //creates the array ($e) of each element
echo '<ul>';
foreach ($e as $each){ //loop the array ($e)
echo '<li>'.$each.'</li>';
}
echo '</ul>';

PHP - why is generating a text area per line when attempting to echo in a text area?

Why can not I make an echo inside a textarea after doing a foreach? the echo happens yes, but everything comes in fragments, one line in each text area.
Why does not everything come out in the same text area?
$array = end($matches);
$array = array_unique($array, SORT_REGULAR);
foreach ($array as $strX) {
$strX = 'myprefix'.$strX.'<br>';
//echo $strX;
echo '<textarea>'.$strX.'</textarea>';
}
Concatenate the value and then echo into the textarea.
$value = null;
foreach ($array as $strX) {
$value .= 'myprefix'.$strX.PHP_EOL;
}
echo '<textarea>'.$value.'</textarea>';
https://3v4l.org/KZn2M
As I understood you so far. You just need to put the beginning tag of textarea before the for-loop. So your code would become:
$array = end($matches);
$array = array_unique($array, SORT_REGULAR);
echo '<textarea>';
foreach ($array as $strX) {
$strX = 'myprefix'.$strX.'<br>';
//echo $strX;
}
echo '</textarea>';
Try this, put textarea outsside loop
$array = end($matches);
$array = array_unique($array, SORT_REGULAR);
echo '<textarea>';
foreach ($array as $strX) {
$strX = 'myprefix'.$strX.'<br>';
//echo $strX;
}
echo '</textarea>';

PHP - Split an array into chunks.

I have a variable on my page called, $recipe['ingredients'];
inside the var you have as follows,
100ml milk, 350ml double cream, 150ml water
and so on. Now 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 for some reason it doesn't work and I do not have the experience with explode to fix it.
$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
$li = '<ul>';
foreach($ingredientsParts as $key=>$value){
$li.=" <li>$value</li>";
}
$li.= '</ul>';
echo $li;
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
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.
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>";
}
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>";
}
if (!empty($recipe['ingredients'])) {
echo '<ul><li>' . implode('</li><li>', explode(', ', $row_rs_recipes['ingredients'])) . '</li></ul>';
}
You can do this:
$ingredients = explode(',', $row_rs_recipes['ingredients']);
$list = '<ul>';
foreach ($ingredients as $ingredient)
{
$list .= '<li>' . $ingredient . '</li>';
}
$list .= '</ul>';
echo $list;

JSON String add Link

I´ve got the a php that returns a JSON string:
$recipes = json_encode($arr);
That is my php-code how I output the recipe-title:
<?php
include('php/getAllRecipes.php');
$jsonstring = $recipes;
$recip = json_decode($recipes, true);
$i = 1;
var data = include('php/getAllRecipes.php')Data.Recipes;
foreach ($recip['Data']['Recipes'] as $key => $recipe) {
echo "$i.) &nbsp ";
echo $recipe['TITLE'];
$i = $i + 1;
echo "<br>";
}
?>
Now, I need to add a href to each title. The href should contain a link to recipe_search.php and I have to give it the id of each recipe.
How can I add this href?
<?php
include('php/getAllRecipes.php');
$jsonstring = $recipes;
$recip = json_decode($recipes, true);
?>
<ol>
<?php
foreach ($recip['Data']['Recipes'] as $key => $recipe) {
echo '<li>
<a href="/recipe_search.php?id=' . $recipe['ID'] . '">
' . $recipe['TITLE'] . '
</a>
</li>';
}
?>
</ol>
Use an ordered list (<ol>) instead of trying to create one yourself using a counter.
var data = include('php/getAllRecipes.php')Data.Recipes; is not valid PHP.
I assume that the id of the recipe is in $recipe['ID'].
Here you are...
foreach ($recip['Data']['Recipes'] as $key => $recipe)
{
// I guess $key is ID of your recipe...
echo sprintf('%d.) %s<br />', $i++, 'recipe_search.php?id=' . $key, $recipe['TITLE']);
}
Thats worked for me, just to test the above:
<?php
$i = 1;
foreach (array_fill(0, 40, 'recipe') as $key => $recipe)
{
// I guess $key is ID of your recipe...
echo sprintf('%d.) %s<br />', $i++, 'recipe_search.php?id=' . $key, $recipe);
}
?>

Categories