Use $I++ more than once in a loop - php

I need to use the value for $i++ in numerous places but if I do that then some fields end up skipping values and instead of being 1, 2, 3 etc. they are 1, 3, 5 and the other field has values of 2, 4, 6 etc.
<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
<div>This number: <?php echo $i++; ?></div>
<div>Should be the same as this one: <?php echo $i++; ?></div>
<?php end while; ?>
It works if I create another variable but this feels like a hack.
<?php $i = 1;
$x = 1;
?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
<div>This number: <?php echo $i++; ?></div>
<div>Should be the same as this one: <?php echo $x++; ?></div>
<?php end while; ?>
Is there a better way?

You can do the increment as a discrete step at the end of the loop, this means you can use it in various places without wondering when you changed the value...
<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ):
the_row(); ?>
<div>This number: <?php echo $i; ?></div>
<div>Should be the same as this one: <?php echo $i; ?></div>
<?php $i++; ?>
<?php end while; ?>

The solution is simple - increase $i only once:
<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
<div>This number: <?php echo $i; ?></div>
<div>Should be the same as this one: <?php echo $i++; ?></div>
<?php end while; ?>

A clean approach would be to echo the value of $i in your loop, and only increase it at the end, as a step alone. This is a good approach to have not only in PHP but in programming in general.
<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
<div>This number: <?php echo $i; ?></div>
<div>Should be the same as this one: <?php echo $i; ?></div>
<?php
$i++;
end while; ?>

Related

Limit this PHP foreach statement to just 5 loops

How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.
<?php if(!empty($locations)): foreach($locations as $location): ?>
<?php if(empty($location["title"])) continue; ?>
<li>
<a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
<?php esc_html_e($location["title"]) ?>
</a>
<?php if($param->count): ?>
<div class="wpjb-widget-item-count">
<div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>
You can use array_slice() first to get a new array with no more than 5 elements.
$locations = array_slice($locations, 0, 5);
Then everything unchanged.
There are three methods:
Method 1: foreach with a counter var
$counter = 1;
foreach($locations as $location) {
// use $location here
if($counter++ == 5) {
break;
}
}
Method 2: foreach using $key=>$val
foreach($locations as $key=>$val) {
// Your content goes here
if($key === 4) {
break;
}
}
Method 3: for loop
for($i = 0; $i < 5; $i++) {
// Use $locations[$i] here and do something with it
}
Using a counter variable into your loop you can control/limit to any number.
Example:
$counter = 0;
foreach($locations as $location):
if($counter++ == 5):
break;
// Your other content goes here
endif;
endforeach;
Add a variable ... increment it each iteration ... after reach 5 just break loop.
<?php $i = 1;?>
<?php if(!empty($locations)): foreach($locations as $location): ?>
<?php if(empty($location["title"])) continue; ?>
<li>
<a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
<?php esc_html_e($location["title"]) ?>
</a>
<?php if($param->count): ?>
<div class="wpjb-widget-item-count">
<div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
</div>
<?php endif; ?>
</li>
<?php if ($i++ == 5) break; ?>
<?php endforeach; ?>
You can use for():
<?php if(!empty($locations)):
for($i=0; $i<5; $i++) {
$location = $locations[$i];
<?php if(empty($locations["title"])) continue; ?>
<li>
<a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
<?php esc_html_e($location["title"]) ?>
</a>
<?php if($param->count): ?>
<div class="wpjb-widget-item-count">
<div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
</div>
<?php endif; ?>
</li>
}

PHP Using single Count++ on both loop/conditional & static content?

Is it possible to use count++ and print it without conditionals or loop?
Normally I use it on conditionals/loop like example:
<?php $count = 1; { while( have_rows('test') ): the_row(); ?>
Text <?php echo $count;?>
<?php $count++;?>
<?php endwhile; }?>
But I want it to use it in stuff like this:
<?php $count = 1; {?>
Static Text <?php echo $count;?>
Static Text <?php echo $count;?>
<?phpwhile( have_rows('test') ): the_row(); ?>
Loop Text <?php echo $count;?>
<?php endwhile;?>
<?php $count++;?>
<?php}?>
How to make the counting work on both static & loop contents?

Need to add a counter in php to separate the rows every 4 columns

I have this code, and I need to close a row every 4 post. Every post is inside a div. I tried some things but I coudn't implement to my code.
<?php
echo "<div class='row'>";
global $post;
$all_events = tribe_get_events(
array(
'eventDisplay'=>'upcoming',
//'posts_per_page'=>10,
)
);
foreach($all_events as $post) {
setup_postdata($post);
?>
<div class="col-sm-3">
<span class="event-date"><?php echo tribe_get_start_date($post->ID, true, 'j M'); ?></span>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) { ?>
<div class="event-thumb">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<div class="event-excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="event-content">
<?php the_content(); ?>
</div>
<?php } ?>
</div>
<?php } //endforeach ?>
<?php wp_reset_query(); ?>
<?php
echo "<div class='row'>";
global $post;
$all_events = tribe_get_events(
array(
'eventDisplay'=>'upcoming',
//'posts_per_page'=>10,
)
);
$count = 1;
foreach($all_events as $post) {
setup_postdata($post);
?>
<div class="col-sm-3">
<span class="event-date"><?php echo tribe_get_start_date($post->ID, true, 'j M'); ?></span>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) { ?>
<div class="event-thumb">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<div class="event-excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="event-content">
<?php the_content(); ?>
</div>
<?php } ?>
</div>
<?php
if($count == 4){
echo "<div class='seperator'></div>";
$count =1;
}
?>
<?php $count++; } //endforeach ?>
<?php wp_reset_query(); ?>
I'd actually solve this 100% in CSS, so you don't need any counting or handling inside your PHP code.
Have a look at this JSFiddle.
float: left will cause the single elements to all follow each other (left aligned).
clear: left on every 4 * n + 1-th element (nth-child(4n+1)) will clear this, essentially forcing a line break.
There is one caveat to this: If there's no room for all 4 entries in one row, you'll end up with additional wrapping, which can be avoided by defining a fixed width for the container.
A simplified in-code version for PHP would just count the fields written and add a line break as necessary:
$i = 1; // counter
foreach ($events as $event) { // iterate over all events
if ($i++ % 4 == 0) // a % b will be 0 for 4, 8, etc.
echo '<br />'; // print the line break using whatever HTML you see fit.
print_event($event); // print the actual event
}
You might ask whether I check for the line break before actually printing an event: That's to prevent additional line breaks if the number of entries is a multiple of 4, i.e. I avoid having an empty trailing line.
You need the modulo operator. It works like this:
$i == 0;
foreach($some_array as $some_value){
if ($i % $number_to_divide_by == 0) {
// do something here every nth time
}
$i++;
}

Wordpress Loop For Even/Odd Posts

I have two columns and I want one post type to get distributed to each column evenly. So it’s two side-by-side divs and I want:
Div1 = Post1, Post3, Post5
Div2 = Post2, Post4, Post6
So basically get odd/even posts. Not exactly sure how to do it.
<?php query_posts('post_type=post-type'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div class="column1">
<?php
//Get Odd Posts
?>
</div>
<div class="column2">
<?php
//Get Even Posts
?>
</div>
<?php endwhile; ?>
<?php else : ?>
//Something that happens when a post isn’t found.
<?php endif; ?>
You want to use the modulus operator something like this:
<?php
$i = 0;
for ($i = 0; $i <20; $i++){
$class = $i % 2 == 0 ? "even" : "odd";
echo "<div class='" . $class . "'>";
echo "</div>";
}
?>
To do what you want, first you have to store the results somewhere (as even/odd), then display them.
Though you should really target these posts with CSS, not PHP, as it's hackish at best.
<?php query_posts('post_type=post-type'); ?>
<?php if (have_posts()) : ?>
<?php
$i = 0;
while (have_posts())
{
$key = $i & 1 ? 'odd' : 'even';
$post[$key] = array(get_the_title() => get_the_content());
$i++;
}
?>
<div class="column1">
<?php foreach ($post['even'] as $title => $content) : ?>
<?php echo $title; ?>
<?php echo $content; ?>
<?php endforeach; ?>
</div>
<div class="column2">
<?php foreach ($post['odd'] as $title => $content) : ?>
<?php echo $title; ?>
<?php echo $content; ?>
<?php endforeach; ?>
</div>
<?php else : ?>
//Something that happens when a post isn’t found.
<?php endif; ?>

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

Categories