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);
Related
This question already has answers here:
PHP Implode wrap in tags
(3 answers)
Closed 11 months ago.
I'd like to create a string variable from an array.
Here's a non working code for conceptualizing it:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
$myString = foreach ( $list as $element ){
'<span>' . $element . '</span><span>|</span>';
};
You can do something like this
<?php
$lists = array("elem1", "elem2", "elem3", "elem4");
$string = '';
foreach ($lists as $element){
$string = $string . ' | '. $element;
};
echo '<span>' . $string . '</span>';
?>
$list = array('elem1', 'elem2', 'elem3', 'elem4');
foreach( $list as $element ){
$myString[] = '<span>' . $element . '</span><span>|</span>';
}
print(implode('', $myString));
What you could do is concatenate the results of each iteration of your loop to a variable that exists outside of the loop.
Example:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
$myString = '';
foreach ( $list as $element ){
$myString .= $myString . '<span>' . $element . '</span><span>|</span>';
};
print($myString);
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
}
?>
This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 9 years ago.
My original string is
one,two,three,four,five,
I need separate each word as a link
one, two, three, ...
My code is
$plat = $row['reg'];
foreach ($plat as $key => $pv) {
$pl[] = implode(',', $pv);
}
for ($p = 1; $p = sizeof($pl); $i++) {
echo '' . $pl[i] . '';
}
This would suffice..
<?php
$str='one,two,three,four,five';
$arr=explode(',',$str);
foreach($arr as $val)
{
echo "<a href=''>$val</a>, ";
}
OUTPUT :
<a href=''>one</a>, <a href=''>two</a>, <a href=''>three</a>, <a href=''>four</a>, <a href=''>five</a>
<?php
$str='one two three four five';
$arr=explode(' ',$str);
foreach($arr as $val)
{
echo "<a href=''>$val</a>, ";
}
this Code to separate blank spacesepration
$string = 'one,two,three,four,five';
$tag_open = '<a href="#" rel="tag">';
$tag_close = '</a>';
echo $tag_open. implode($tag_close.', '.$tag_open, explode(',', $string)). $tag_close;
Try this code:
$plat=$row['reg'];
foreach ($plat as $key=> $pv) {
$pl[] = explode(',', $pv);
for($p=1;$p=sizeof($pl); $i++) {
echo ''.trim($pl[i]).'';
}
}
I am trying to take a string like...
php,mysql,css
and turn it into .. #php #mysql #css
What I have so far...
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
foreach($hashTags as $k => $v){
$hashTagsStr = '';
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
?>
Problem is it only prints #css
How about this:
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagStr = '#' . implode( ' #', $hashTags );
...or:
$hashTagStr = "php,mysql,css";
$hashTagStr = '#' . str_replace( ',', ' #', $hashTagStr );
That's because every time the loop runs you're clearing out $hashTagsStr by doing:
$hashTagsStr = '';
Change it to:
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
Pass your values by reference:
$hashTags = array("php","mysql","css");
foreach ( $hashTags as &$v ) $v = "#" . $v;
Then hammer out the results:
// #php #mysql #css
echo implode( " ", $hashTags );
Demo: http://codepad.org/zbtLF5Pk
Let's examine what you're doing:
// You start with a string, all good.
$hashTagStr = "php,mysql,css";
// Blow it apart into an array - awesome!
$hashTags = explode( "," , $hashTagStr );
// Yeah, let's cycle this badboy!
foreach($hashTags as $k => $v) {
// Iteration 1: Yeah, empty strings!
// Iteration 2: Yeah, empty...wait, OMG!
$hashTagsStr = '';
// Concat onto an empty var
$hashTagsStr .= '#'.$v.' ';
}
// Show our final output
echo $hashTagsStr;
looks like a Job for array_walk
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
array_walk($hashTags, function(&$value){ $value = "#" . $value ;} );
var_dump(implode(" ", $hashTags));
Output
string '#php #mysql #css' (length=16)
You should move the $hashTagsStr = '' line outsite the foreach loop, otherwise you reset it each time
You are defining the variable $hashTagsStrinside the loop.
<?php
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
Anyway, I think this would be simpler:
<?php
$hashTagStr = "php,mysql,css";
$hashTagStr = '#' . str_replace(',', ' #', $hashTagStr);
echo $hashTagStr;
During each iteration of the loop, you are doing $hashTagsStr = '';. This is setting the variable to '', and then appending the current tag. So, when it's done, $hashTagsStr will only contain the last tag.
Also, a loop seems like too much work here, you can much easier just replace the , with #. No need to break it into an aray, no need to loop. Try this:
$hashTagStr = "php,mysql,css";
$hashTagStr = '#'.str_replace(',', ' #', $hashTagStr);
function prepend( $pre, $array )
{
return array_map(
function($t) use ($pre) { return $pre.$t; }, $array
);
}
What you semantically have in your string is an array. ➪ So better explode as soon as possible, and keep working with your array, as long as possible.
Closures & anonymous functions as shown work in PHP 5.4+.
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;