Remove comma on last item of foreach - php

I have next code for WordPress loop of tags for single post:
<?php if ($tags) : foreach($tags as $tag): ?>
<a href="<?php echo get_tag_link($tag); ?>">
<?php echo $tag->name; ?>
</a>,
<?php endforeach; endif; ?>
I have comma added to last anchor. There is also white space after comma.
How can I remove the comma from last anchor while I am doing this with foreach() PHP loop?
Thanks for ideas and help!

Check if your loop is working on the last one:
<?php if ($tags) : ?>
<?php $count = count($tags); ?>
<?php foreach($tags as $i => $tag): ?>
<a href="<?php echo get_tag_link($tag); ?>">
<?php echo $tag->name; ?>
</a>
<?php if ($i < $count - 1) echo ", "; ?>
<?php endforeach; ?>
<?php endif; ?>

What has a higher cost, calling a function or setting a variable? Here's another way to do it perhaps, which sets a variable and removes the offending chars at the end - no extra math or if checks needed.
<?php
$tagoutput = '';
if ($tags) {
foreach ($tags as $tag)
$tagoutput .= '' . $tag->name . ', ';
$tagoutput = rtrim($tagoutput, ', ');
}
echo $tagoutput;
?>

You can do it the other way around (remove it from the first one). If your array is numeric you can try something like this:
<?php if ($tags): ?>
<?php foreach ($tags as $key => $tag): ?>
<?php if ($key > 0): ?>,<?php endif ?>
<a href="<?php echo get_tag_link($tag); ?>">
<?php echo $tag->name; ?>
</a>
<?php endforeach ?>
<?php endif ?>

You can also try it using counter.
$values = array('value','value','value');
$count = count($values);
$i = 0;
foreach($values as $value){
$i++;
echo $value;
if($count > $i){
echo ', ';
}
}
Output: value, value, value

Related

Blankline after foreach loops

I have this foreach loop:
echo '';
foreach ($r['result']['achievements']['0']['achievements'] as $item) {
echo '
<div class="achiev-title"> ', $item['title'], '</div>
<div class="description"> ', $item['description'], '</div>
<div class="criteria">';
if(!empty($item['criteria'])){
foreach ($item['criteria'] as $item2){
echo '<li>
', $item2['description'], ' </li>';
}
}
}
echo '
</div>
<br/>';
?>
I want to have a blankline everytime the two loops are finished. For that i´ve tried the <br/> but without any effect.
Try This :
echo '<div>';
foreach ($r['result']['achievements']['0']['achievements'] as $item)
{
echo '<div class="achiev-title">'.$item['title'].'</div>
<div class="description">'.$item['description'].'</div>
<div class="criteria">';
if(!empty($item['criteria']))
{
foreach ($item['criteria'] as $item2)
{
echo '<li>'.$item2['description'].'</li>';
}
}
echo '</div></br>';
}
echo '</div>';
Your code should be like this
<?php
$r['result']['achievements']['0']['achievements'] = array();
$item['criteria'] = array();
foreach ($r['result']['achievements']['0']['achievements'] as $item) {
echo '<div class="achiev-title"> '. $item['title']. '</div>
<div class="description"> '. $item['description']. '</div>
<div class="criteria">';
if(!empty($item['criteria'])){
foreach ($item['criteria'] as $item2){
echo '<li>'. $item2['description']. ' </li>';
}
}
}
echo '</div><br/>';
?>
Remove line 2 and 3 for your code xD
Looks like you have ended your div and placed your br within the item loop. If you want to print a br after the two loops are finished, then you should print it at the end of the first loop($item loop) brace.
Also, you should try and write cleaner code by separating your HTML and PHP in separate tags instead of echoing out HTML within the PHP itself.
Try this:
<?php foreach ($r['result']['achievements']['0']['achievements'] as $item) { ?>
<div class="achiev-title"><?php echo ', $item['title'], '; ?></div>
<div class="description"><?php echo ', $item['description'], '; ?></div>
<div class="criteria">
<?php if(!empty($item['criteria'])) {
foreach ($item['criteria'] as $item2) {
?>
<li><?php echo ', $item2['description'], '; ?></li>
<?php } // $item2 loop ends ?>
<?php } // if ends ?>
</div>
<?php } // $item loop ends ?>
<br/>
First, it seemed you were using commas(,) were you were supposed to use dots (.) and then single quotes and double quotes here and there. Anyways, you could try a much concise approach that. Here you go:
<?php
foreach ($r['result']['achievements']['0']['achievements'] as $item) { ?>
<div class="achiev-title"><?php echo $item['title']; ?></div>
<div class="description"><?php echo $item['description'] ?></div>
<div class="criteria">
<?php
if(!empty($item['criteria'])){
foreach ($item['criteria'] as $item2){
echo "<li>{$item2['description']}</li>";
}
}
?>
</div>
<?php } ?>

Looping through a PHP array

I have the following PHP array structure:
$set = array();
$set[] = array('firstname'=>'firstname 1',
'lastname'=>'lastname 1',
"bio"=>array('paragraph 1 of the bio, 'paragraph 2 of the bio','paragraph 3 of the bio'),
);
I then access the array with the following:
<?php $counter = 0;
while ($counter < 1) : //1 for now
$item = $set[$counter]?>
<h1><?php echo $item['firstname'] ?></h1>
<h1><?php echo $item['lastname'] ?></h1>
<?php endwhile; ?>
I'm uncertain how I can loop through the "bio" part of the array and echo each paragraph.
So as a final output, I should have two h1s (first and last name) and three paragraphs (the bio).
How can I go about doing this?
Use foreach loop
foreach($item['bio'] as $listitem) {
echo $listitem;
}
You don't need to use a manual counter, you can use foreach. It's generally the easiest way and prevents off-by-one errors.
Then you need a second inner loop to loop through the bio.
<?php foreach ($set as $item): ?>
<h1><?php echo $item['firstname'] ?></h1>
<h1><?php echo $item['lastname'] ?></h1>
<?php foreach ($item['bio'] as $bio): ?>
<p><?php echo $bio; ?></p>
<?php endforeach; ?>
<?php endforeach; ?>
On a related note; you probably want to look into escaping your output.
Add into the while loop also this:
<?php foreach ($item['bio'] as $paragraph): ?>
<p><?php echo $paragraph; ?></p>
<?php endforeach; ?>
Note that used coding style is not optimal.
Try:
foreach($set as $listitem) {
if(is_array($listitem)) {
foreach($listitem as $v) //as $set['bio'] is an array
echo '<h1>' .$v . '</h1>';
} else
echo '<p>'.$listitem.'</p>';
}

Unable to apply foreach loop properly in PHP

I want two posts at each slide. but getting only one slide. I am new in programming, please help me.
$widget_id = $widget->id.'-'.uniqid();
$settings = $widget->settings;
$navigation = array();
$captions = array();
$i = 0;
?>
<div id="slideshow-<?php echo $widget_id; ?>" class="wk-slideshow wk-slideshow-revista-articles" data-widgetkit="slideshow" data-options='<?php echo json_encode($settings); ?>'>
<div>
<ul class="slides">
<?php foreach ($widget->items as $key => $item) : ?>
<?php
$navigation[] = '<li><span></span></li>';
$captions[] = '<li>'.(isset($item['caption']) ? $item['caption']:"").'</li>';
/* Lazy Loading */
$item["content"] = ($i==$settings['index']) ? $item["content"] : $this['image']->prepareLazyload($item["content"]);
?>
<li>
<article class="wk-content clearfix"><?php echo $item['content']; ?></article>
</li>
<?php $i=$i+1;?>
<?php endforeach; ?>
</ul>
<?php if ($settings['buttons']): ?><div class="next"></div><div class="prev"></div><?php endif; ?>
<?php echo ($settings['navigation'] && count($navigation)) ? '<ul class="nav">'.implode('', $navigation).'</ul>' : '';?>
<div class="caption"></div><ul class="captions"><?php echo implode('', $captions);?></ul>
</div>
</div>
http://i.stack.imgur.com/sy1ih.png
you're missing the { after the foreach and at the end of the loop.
<?php foreach ($widget->items as $key => $item) {
$navigation[] = '<li><span></span></li>';
$captions[] = '<li>'.(isset($item['caption']) ? $item['caption']:"").'</li>';
/* Lazy Loading */
$item["content"] = ($i==$settings['index']) ? $item["content"] : $this['image']->prepareLazyload($item["content"]);
?>
<li>
<article class="wk-content clearfix"><?php echo $item['content']; ?></article>
</li>
<?php
$i=$i+1;
}
?>
Your foreach syntax looks fine. That syntax is a lot easier for some people to read when embedded in HTML than the traditional braces.
Can I ask what the $this variable refers to? I don't see this instantiated anywhere in your code? Is it supposed to be $item instead?
$settings['index'] never changes within the loop, however $i does.
Change to: ($i<2)

Remove "," at end of foreach loop

I've created a loop to list a set of meta values. I've been able to apply a class to the last item in the list, but I'd like to remove the "," at the end of the last value. Any help would be much appreciated.
<?php $count = count($subcategory); $num = 0; ?>
<?php foreach ($subcategory as $subcategory): ?>
<p
<?php if($num == $count-1){ ?>
class="subcategory-item subcategory-last-item inline-block"
<?php } ?>
class="inline-block subcategory-item"> <?php echo $subcategory;?>,</p>
<?php $num++ ?>
<?php endforeach; ?>
I may be taking an incorrect route by worrying about adding a class to the last item. If I can remove the "," from the last item I'll be happy.
Here's a quick rewrite which may lead you to a solution:
<?php $count = count($subcategories); $num = 0; ?>
<?php $classes = 'inline-block subcategory-item'; ?>
<?php foreach ($subcategories as $subcategory): ?>
<p class="<?=$classes.($num==$count-1?' subcategory-last-item':'')?>">
<?php echo $subcategory;?>
<?php if ($num<$count-1): ?>
,
<?php endif; ?>
</p>
<?php $num++ ?>
<?php endforeach; ?>

how to add big space

<?php foreach ($rows as $id => $row): ?>
<li class="<?php print $classes[$id]; ?>"><?php print $row; ?></li>
<?php endforeach; ?>
the above code is used to output an article list. now i want to add big space after the lines which is the multiple of 10.namely,add a big space (eg:margin-bottom:30px,only to after every 10 bullet points but the space between other li is 15px )after every 10 bullet points. how to change the above code. then i can use css to get that.
–
Although I don't have a clue what you mean by 'big space', I assume you want to place an arbitry HTML tag after every 10th list item. You can do this like so, for example:
<?php $i = 0; ?>
<?php foreach ($rows as $id => $row): ?>
<li class="<?php print $classes[$id]; ?>"><?php print $row; ?></li>
<?php if ($i++ === 10): ?><br /><?php $i = 0; endif; ?>
<?php endforeach; ?>
EDIT, you clarified:
no,eg:30px, but the space between other <li> is 20px.
Which can be done like so:
<?php $i = 1; ?>
<?php foreach ($rows as $id => $row): ?>
<?php $i++; ?>
<li style="margin-bottom:<?php echo ($i === 10) ? : '30' : '20'); ?>px;" class="<?php print $classes[$id]; ?>"><?php print $row; ?></li>
<?php if ($i === 10) $i = 1; ?>
<?php endforeach; ?>
The modulus operator (%) is ideal for this:
<?php $i = 0; foreach ( $rows as $id => $row ): ?>
<li style="margin-bottom: <?php echo $i ++ % 10 ? '30' : '20' ?>px;" class="<?php echo $classes[$id] ?>">
<?php echo $row ?>
</li>
<?php endforeach ?>
As a slight amendment to Aron's code, if you wanted to use CSS to style the <li>:
<?php $i = 1;
foreach ($rows as $id => $row):
if($i === 10){
$end_class = ' end-class';
$i = 1;
} else {
$end_class = '';
$i++;
}
echo '<li class="' . $classes[$id] . $end_class . '">' . $row . '</li>';
endforeach;
?>
You can then apply the style to .end-class.

Categories