Add comma after value only if more than one value? - php

Im trying to echo a set of values for categories. What I'd like to do is if there are more than one value, append a comma afterwards. Here's a snippet of what I have:
<?php foreach((get_the_category()) as $category) { echo $category->cat_name . ', '; } ?>
The problem with this is that categories with one value will have a comma at the end.

Alternative 1
Add all values to an array and then just use implode() to glue them all together:
$catArray = [];
foreach((get_the_category()) as $category) {
$catArray[] = $category->cat_name;
}
// Now we can implode the array, using , as the glue
echo implode(', ', $catArray);
Alternative 2
You could also prepend the commas in your loop so you don't need any if-statements:
$glue = '';
foreach((get_the_category()) as $category) {
echo $glue . $category->cat_name;
$glue = ', ';
}
or a shorter version (not as readable though and requires PHP 7+):
foreach((get_the_category()) as $category) {
echo ($glue ?? '') . $category->cat_name;
$glue = ', ';
}
The first iteration won't get any comma in front of it, but the rest will.

You could get the count of results from get_the_category(), set a counter and increment that each time through the loop. Check if $i is equal to the count and if it is, don't add the comma.
Assuming that function is countable and you don't need checks to make sure their aren't 0 results:
<?php
$count = count(get_the_categories());
$i = 1;
foreach((get_the_category()) as $category) {
if($i < $count) {
echo $category->cat_name . ', ';
} else {
echo $category->cat_name;
}
$i++;
}
?>

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

Add the correct number of commas

This script displays the categories of a post, but excludes the ones that the user doesn't want to show:
function exclude_post_categories($excl='', $spacer=' ') {
$categories = get_the_category($post->ID);
if (!empty($categories)) {
$exclude = $excl;
$exclude = explode(",", $exclude);
$thecount = count(get_the_category()) - count($exclude);
foreach ($categories as $cat) {
$html = '';
if (!in_array($cat->cat_ID, $exclude)) {
$html .= '<a href="' . get_category_link($cat->cat_ID) . '" ';
$html .= 'title="' . $cat->cat_name . '">' . $cat->cat_name . '</a>';
if ($thecount > 1) {
$html .= $spacer;
}
$thecount--;
echo $html;
}
}
}
}
The fuctions is triggered like this.
<?php exclude_post_categories('5', ', ');
So if a post has the categories: 1,2,3,4,5 than only 1,2,3,4 are echoed.
The script works great for the posts that have the category that is excluded (5).
The problem lies with the posts that don't have that category.
So if a post has the categories: 1,2,3,4 that those are echoed but with less commas than needed: 1,2,34
$thecount variable is always calculated wrong for the posts that don't have the category that has to be excluded.
Try something like this:
$existing = get_the_category();
$newcategories = array_udiff($existing,$exclude,function($e,$x) {
return $e->cat_ID != $x;
});
$as_links = array_map(function($c) {
return '<a href="'.get_category_link($c->cat_ID).'" '
.'title="'.$cat->cat_name.'">'.$cat->cat_name.'</a>';
},$newcategories);
echo implode($spacer, $as_links);
This will first strip out categories whose IDs are in the $exclude array, then convert each category to a category link, before outputting them with the separator.
EDIT: Slightly mis-read the question. This expects $exclude to be an array. Put the following line at the start:
if( !is_array($exclude)) $exclude = array($exclude);
To make it support single-value inputs as well - this way you can either specify one or many categories to exclude.
Found a better solution to the problem here: http://css-tricks.com/snippets/wordpress/the_category-excludes/#comment-1583708
function exclude_post_categories($exclude="",$spacer=" ",$id=false){
//allow for specifiying id in case we
//want to use the function to bring in
//another pages categories
if(!$id){
$id = get_the_ID();
}
//get the categories
$categories = get_the_category($id);
//split the exclude string into an array
$exclude = explode(",",$exclude);
//define array for storing results
$result = array();
//loop the cats
foreach($categories as $cat){
if(!in_array($cat->cat_ID,$exclude)){
$result[] = "$cat->name";
}
}
//add the spacer
$result = implode($spacer,$result);
//print out the result
echo $result;
}

Concatenating array rows php

This may be a stupid question, so please go easy on me if so.
I have a range of queries (MySQL) returning multidimensional arrays.
I then use these array items to populate variables in a string in a foreach loop.
I then need this string to populate a javascript graph so the format of the data wants to be perfect. this idea works with 1 multidimensional array.
However. To do multiple graphs (e.g comparison line graph) I need to express all the data in the same row.
So what I need to be able to do is if possible merge row to row of the array, rather than add it to the end.
Ill show you my working:
foreach ($graph_month as $month) :
$first .= ' { year: "'.$month['month'].'",';
endforeach;
foreach ($graph_data1 as $data) :
$second1 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data2 as $data) :
$second2 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data3 as $data) :
$second3 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data4 as $data) :
$second4 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
foreach ($graph_data5 as $data) :
$second5 .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
So each of the foreach's is populating a little section of the javascript required, however I need to be able to concatenate all these rows on the right of each other.
e.g
a foreach that can produce:
$first.$second1.$second2.$second3.$second4.$second5
Is this possible, would it be possible to add [i] and [i++] to each variable.
To start with, you could eliminate the extra foreach lines by generating variables like this:
foreach ($graph_month as $month):
for ($i = 1; $i <=5; $i++) {
//$graph_data$i becomes $graph_data1, then $graph_data2 etc.
foreach ($graph_data$i as $data) :
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
endforeach;
}
// and so on
endforeach;
The outcome of this script is, as you requested, something of this shape:
{year: month, title: value title: value
We can tweak it a little like this:
foreach ($graph_month as $month):
$variable .= ' { year: "'.$month['month'].'",';
for ($i = 1; $i <=5; $i++) {
//$graph_data$i becomes $graph_data1, then $graph_data2 etc.
foreach ($graph_data$i as $data) :
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
if ($i != 5) {
$variable .= ", ";
}
endforeach;
}
$variable .=
// and so on
endforeach;
and it becomes:
{ year: month, 'title': 'value', 'title': 'value', ... }
You can put same variable:
foreach ($graph_month as $month) {
$variable .= ' { year: "'.$month['month'].'",';
}
foreach ($graph_data1 as $data) {
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
}
foreach ($graph_data2 as $data) {
$variable .= ' "'.$data['title'].'": '.$data['totalValue'].' ';
}
// and so on
they will concatenate on every loop.
You can use the for loop like this...
<?php
for($i=0;$i<count($graph_month);$i++)
{
$all_values1 = $graph_data1[$i]['title'] . $graph_data1[$i]['totalValue'];
$all_values2 = $graph_data2[$i]['title'] . $graph_data2[$i]['totalValue'];
$all_values3 = $graph_data3[$i]['title'] . $graph_data3[$i]['totalValue'];
$all_values4 = $graph_data4[$i]['title'] . $graph_data4[$i]['totalValue'];
$all_values5 = $graph_data5[$i]['title'] . $graph_data5[$i]['totalValue'];
}
?>
No need to run too may for loop. It will take some extra time to execute...
Try like this....
Use Empty String
$string = '';
Then use this variable with every for loop
foreach($array1 as $value){
$string.= $value['some_data'];
}
foreach($array2 as $value){
$string.= $value['some_data'];
}
Use this $string as final result
Let PHP worry about the JSON formatting just build the object correctly.
<?php
$tojson = array(
0 => array(),
1 => array(),
2 => array(),
3 => array(),
4 => array(),
5 => array()
);
foreach($graph_month as $month)
$tojson[0]['year'] = $month['month'];
foreach($graph_data1 as $data)
$tojson[1][$data['title']] = $data['totalValue'];
foreach($graph_data2 as $data)
$tojson[2][$data['title']] = $data['totalValue'];
foreach($graph_data3 as $data)
$tojson[3][$data['title']] = $data['totalValue'];
foreach($graph_data4 as $data)
$tojson[4][$data['title']] = $data['totalValue'];
foreach($graph_data5 as $data)
$tojson[5][$data['title']] = $data['totalValue'];
$json = json_encode($tojson);
?>

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;

Function for obtain the first 3 tag names on a post

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.

Categories