How to remove the last comma from foreach loop? - php

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
}
?>

Related

How do i display list items from php array

Ive been trying make this display as html list items it just a string that i explode then loop over each item i cant get it to out put correctly. Could some one please show me where im going wrong or suggest an new approch.
this is what ive tried
$path = "1/2/3/4";
$expath = explode("/",$path);
$ret = '';
echo '<ul>';
foreach ($expath as $pitem) {
echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
}
echo '</ul>';
.
Desired out put on hrefs
1
1/2
1/2/3
1/2/3/4
Desired visual out LIs
1
2
3
4
Output i get be warned
1
12/>212/>23/>312/>23/>34/>4
$path = "1/2/3/4";
$expath = explode("/", $path);
echo '<ul>';
foreach ($expath as $i => $pitem) {
$slice = array_slice($expath, 0, $i + 1);
$path = implode('/', $slice);
echo '<li>' . $pitem . '</li>';
}
echo '</ul>';
$list = explode("/", "1/2/3/4");
This will create an array $list as:
echo $list[0]; // 1
echo $list[1]; // 2
echo $list[2]; // 3
echo $list[3]; // 4
This line is the problem: echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
Should be formatted like:
echo "<li><a href='{$ret}={$pitem}/'>{$pitem}</a></li>";
or echo '<li>'.$pitem.'</li>';
Its because your $ret. Place that inside the loop. In your code you concatenate $pitem with $ret all older $ret values also get concat.
Try
<?php
$path = "1/2/3/4";
$expath = explode("/",$path);
echo '<ul>';
foreach ($expath as $pitem) {
$ret = '';
echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
}
echo '</ul>';
If you want = sign tobe there in the url then just change echo by following
echo "<li><a href='$ret=$pitem/'>$pitem</a></li>";
PHP echo with double quotes will print variable value.

Explode to array and print each element as list item

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

Why am I getting extra white space when I remove the last comma?

I used several different posts on this site to figure out how to remove the last comma in a string. Apparently it's a classic question, but what I can't figure out is why it's adding an extra white space before the comma and not after the comma as one would expect?
As always I've played around with the code but I can't figure out where the extra white space comes from, please help me I'm going blind!
<?php $comma = ""; ?><?php foreach ($tags as $tag) { ?>
<?php echo $comma; ?><a href="<?php echo $tag['href']; ?>">
<?php echo $tag['tag']; ?></a><?php $comma = ","; ?>
The blank space is due to the line break in your HTML after the <a> element opens.
A better output soution would be:
<?php
$total = count( $tags);
$x = 0;
foreach ( $tags as $tag ){
$x++;
echo '' . $tag['tag'] . '';
if ( $x < $total ) echo ',';
}
?>
Perhaps you have a white space in your HTML code between the PHP tags... Why don't you rewrite it to something like this:
<?php $comma = '';
foreach ($tags as $tag) {
echo "$comma<a href='{$tag['href']}'>{$tag['tag']}</a>";
$comma = ',';
} ?>
I would rather write the whole thing as such:
<?php
$tag_strings = array();
foreach ($tags as $tag)
{
$tag_strings[] = "<a href='" . $tag['href'] . "'>" . $tag['tag'] . "</a>";
}
echo implode(',', $tag_strings);

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);
}
?>

Print in foreach with comma [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Removing last comma in PHP?
So I have the following code:
<?php
foreach ($movie->Genres as $genre):
?>
<?=$genre->name?>,
<?php
endforeach;
?>
And this will give me the following: Action, Drama, Crime, but I don't need this last comma separator - so my question is what would be the best way to avoid that comma ?
Ps.
If that matters I have 4 loops like this one on my page - for actors, directors, etc.
Write you A-tags to an array and join the items.
<?php
$items = array();
foreach ($movie->Genres as $genre):
$items[] = '' . $genre->name . '';
endforeach;
echo join(', ', $items);
?>
$temp = array();
foreach($movie->Genres as $genre) {
$temp[] = <<<EOL
{$genre->name}
EOL;
}
echo implode(',', $temp);
The other option is to use string concatenation, then a substring to delete the trailing comma:
$temp = '';
foreach(...) {
$temp .= ...
}
echo rtrim($temp, ',');
$a = array();
foreach ( $movie->Genres as $v ){
$a[] = '' . $v->name . '';
}
$s = implode(',', $a);
var_dump($s);

Categories