I loop through my array to print the articles names:
<?php
if ($articles) {
foreach($articles as $article) {
echo $article->name.", ";
} // end foreach article
} // end if has articles
?>
This will obviously produce something like
Apple, Banana, Mango,
But I am looking for:
Apple, Banana, Mango
I tried some implode statement like this:
<?php
if ($articles) {
foreach($articles as $article) {
echo implode(", ", $article->name);
} // end foreach article
} // end if has articles
?>
or
<?php
if ($articles) {
echo implode(", ", $articles->article->name);
} // end if has articles
?>
None of these are working for me. How can do it right? Thanks for hints!
You can use foreach to add the article names to an array, then implode() that array of names.
<?php
if ($articles) {
$article_names = array();
foreach($articles as $article) {
$article_names[] = $article->name;
} // end foreach article
echo implode(', ', $article_names);
} // end if has articles
?>
it's much more easy to check for your first loop-iteration, wrte the comma before your text and leave this comma aout on the first iteration:
<?php
if ($articles) {
$firstiteration = true:
foreach($articles as $article) {
if(!$firstiteration){
echo ", ";
}
$firstiteration = false;
echo $article->name;
} // end foreach article
} // end if has articles
?>
another (more beautiful in my optionion) possibility would be to override the _toSting()-method of your article-class:
...
function __toString(){
return $this->name;
}
...
and simply echo implode(", ",$articles)
It is better way to do what you want:
<?php
$string = '';
if ($articles) {
foreach($articles as $article) {
$string .= $article->name.", ";
}
}
$string = substr($string, 0, -2);
echo $string;
?>
PHP has a lot of good array functions, and this screams for one of them.
$namesArray = array_map(function($x){return $x->name;}, $articles);
$string = implode(',' $namesArray);
OR
$first = true;
array_walk(function($x) use (&$first)
{
if(!$first) {echo ', ';} else{$first = false;}
echo $x->name;
}, $articles);
I really like the above response with the __toString function also, but I wanted to show these array functions because i think they are often underused in favor or unnecessary foreach loops.
You can remove last comma and space by using trim function. It is the easiest way..
<?php
if ($articles) {
foreach($articles as $article) {
echo trim(implode(", ", $article->name), ', ');
}
}
?>
Related
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
}
?>
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>';
I have a list of names and each name consist of 2-4 words: name, (if exist) middle name(s), surname.
These are the names:
Ali Yilmaz
Taha Ugur Unal
Omer Ibrahim Tahsin Son
Recai Sahin
etc.
I want to print this names as this: Surname, name middle name(s) (if exist)
The names above will be:
Ali Yilmaz -> Yilmaz, Ali
Taha Ugur Unal -> Unal, Taha Ugur
Omer Ibrahim Tahsin Son -> Son, Omer Ibrahim Tahsin
Recai Sahin -> Sahin, Recai
etc.
If I had only one name I can use that code:
<?php $exp1 = explode(" ", $author1); ?>
<?php if (count($exp1) == 2) {?>
<?php print ($exp1[1] .', ' .$exp1[0]); ?>
<?php } elseif (count($exp1) == 3) {?>
<?php print ($exp1[2] .', ' .$exp1[0] .' ' .$exp1[1]); ?>
<?php } elseif (count($exp1) == 4) {?>
<?php print ($exp1[3] .', ' .$exp1[0] .' ' .$exp1[1] .' ' .$exp1[2]); ?>
<?php }?>
Each page can have different numbers of author and I thought I could use foreach to apply the above code for each author name but I couldn't do this.
I tried a piece of code such that:
<?php foreach $author as $obj): ?>
<?php $a = explode (" ", $obj) ?>
<?php endforeach ?>
...
But it gives error:
explode() expects parameter 2 to be string, array given.
How can I do this?
<?php
$names = array(
'Ali Yilmaz',
'Taha Ugur Unal',
'Omer Ibrahim Tahsin Son',
'Recai Sahin'
);
// First you should iterate through:
foreach ($names as $name) {
// and now, let make the job
// split by words
$parts = explode(' ', $name);
if (count($parts) == 1) {
echo "{$name}<br/>";
continue;
}
// get last word
$last = array_pop($parts);
// Print last one, comma, and rest of name
echo "{$last}, " . implode(' ', $parts) . "<br/>";
}
If you had a single string, you would
split all the words with explode().
take out the surname and store it.
join the rest of the name with implode().
See the example below:
<?php
$name = "Son of the Mask";
$words = explode(" ", $name); // split the string wherever there is a whitespace.
$surname = array_pop($words);
$restOfTheName = implode(" ", $words); // join the words with a whitespace in between them.
echo $surname . ", " . $restOfTheName;
?>
On the other hand, if you have a list of names in an array called, say, $namelist, you can use the foreach() loop to iterate through the list.
You would do something like:
<?php
foreach ($namelist as $name)
{
$words = explode(" ", $name);
$surname = array_pop($words);
$restOfTheName = implode(" ", $words);
echo $surname . ", " . $restOfTheName;
}
?>
Hope that helped :-)
EDIT:
And no, you need not use <?php and ?> on every line. This is only helpful, say when you want to use small snippets of PHP inside your HTML tags.
For example, let us say you want to display some information in an unordered list. Then you would do something like
<?php
$info1 = "Head over to Google.com";
$info2 = "Search before you post!";
?>
<ul>
<li><?php echo $info1; ?></li>
<li><?php echo $info2; ?></li>
</ul>
But, doing this for a script that contains only PHP code doesn't make sense. Moreover, it renders your code difficult to read, and eats up a lot of your valuable time.
you can try this
<?php
$newNameArray=array();
$namesArray = array(
'Ali Yilmaz',
'Taha Ugur Unal',
'Omer Ibrahim Tahsin Son',
'Recai Sahin'
);
foreach ($namesArray as $name) {
$partsOfName = explode(" ", $name);
//last name
$lastName = array_pop($partsOfName);
// store the name in new array
$newNameArray[]=$lastName.", ".implode(" ", $partsOfName);
}
//show all names
var_dump($newNameArray);
?>
you can see this for details explode and array push
use this
foreach ($author as $obj) {
$nameArr = explode(' ',$obj);
if(count($nameArr) > 1) {
$lname = $nameArr[count($nameArr)-1];
array_pop($nameArr);
echo $lname.", ".implode(' ',$nameArr);
echo "<br />";
} else {
echo $obj;
echo "<br />";
}
}
I am trying to make string serial comma from array. Here is the code I use:
<?php
echo "I eat " . implode(', ',array('satay','orange','rambutan'));
?>
But the results I get:
I eat satay, orange, rambutan
Cannot:
I eat satay, orange, and rambutan
Yet!
So, I made my own function:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
// Reverse array
$ariBlk=array_reverse($ari,false);
foreach($ariBlk as $no=>$c){
if($no>=(count($ariBlk)-1)){
$rturn[]=$c.$delimiter;
}else{
$rturn[]=($no==0)?
$konj.$c
: $space.$c.$delimiter;
};
};
// Reverse array
// to original
$rturn=array_reverse($rturn,false);
$rturn=implode($rturn);
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
Thus:
<?php
$eat = array_to_serial_comma(array('satay','orange','rambutan'));
echo "I eat $eat";
?>
Result:
I eat satay, orange, and rambutan
Is there a more efficient way, using a native PHP function maybe?
Edit:
Based on code from #Mash, I modifying the code that might be useful:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
$akr = array_pop($ari);
$rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr;
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
Here's a much cleaner way:
<?php
$array = array('satay','orange','rambutan');
$last = array_pop($array);
echo "I eat " . implode(', ', $array) . ", and " . $last;
?>
array_pop() takes the last element out of the array and assign it to $last
<?php
$arr = array('satay','orange','rambutan');
print("I eat ".implode(", ", array_slice($arr, 0, count($arr)-1))." and ".$arr[count($arr)-1]);
?>
Try like this:
$array = array('satay','orange','rambutan');
echo "I eat ".join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1))));
Duplicate question: Implode array with ", " and add "and " before last item
<?php
$arr = array('satay','orange','rambutan');
$lastElement = array_pop($arr);
echo "I eat " . implode(', ',$arr)." and ".$lastElement;
?>
This will result the same :
I eat satay, orange and rambutan
How about this?
function render_array_as_serial_comma($items) {
$items = $variables['items'];
if (count($items) > 1) {
$last = array_pop($items);
return implode(', ', $items) . ' and ' . $last;
}
return array_pop($items);
}
This should do the following:
echo render_array_as_serial_comma(array('a'));
echo render_array_as_serial_comma(array('a', 'b'));
echo render_array_as_serial_comma(array('a', 'b', 'c'));
a
a and b
a, b and c
function hashtags(){
$tags = get_the_tags($post->ID);
$count=0;
foreach ($tags as $tag){
$count++;
if (1 == $count) {
return $tag->name . ', ';
}
if (2 == $count) {
return $tag->name . ', ';
}
if (3 == $count) {
return $tag->name;
}
}
}
I don't know about php, i'm noob, i made this function for showing the name of the first 3 tags of post, i want this return: tag1, tag2, tag3.
The function works but only return the first tag, if i put echo no problem but i don't want an echo, any idea?
Sorry if I've misunderstood but I think you're trying to return a comma separated list of the names found by the get_the_tags function? If so this should work:
$tags = get_the_tags($post->ID);
$names = array();
$count = 1;
foreach ($tags as $tag) {
$names[] = $tag->name;
if ($count++ == 3) {
break;
}
}
return implode(', ', $names);
That code loops through the tags, adds each tag name to an array ($names), and finally runs the array through implode() to generate the comma separated list.