I am new to php and I am trying to create a simple bit of code that prints a "last" class at the start of the last element in a "while" loop. There are only two items in the loop (blog excerpts) hence why I have tried below with the if ($i == 1)... Thanks for any help.
Here is my code so far - which only returns the p
<?php
$i = 0;
if($i == 1) {
echo '<p class="last">';
}
else {
echo '<p>';
}
?>
EDIT:
Thanks for the help so far. Greatly appreciated - I have provided a bit more information below (I posted late at night, so I realise I haven't been all that clear).
This is the full piece of code I am trying to write. It is pulling blog excerpts from Wordpress - currently limited to 2 blog articles.
<?php
$posts = new WP_Query('showposts=2');
while ( $posts->have_posts() ) : $posts->the_post();
?>
<p><?php echo the_title(); ?><br/>
<?php echo substr(get_the_excerpt(), 0,200); ?>... Read More</p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
I am wanting to add the class "last" to the p at the start of line 5 - for the last blog except only.
Thanks again.
Nick's answer says almost all that needs to be said.
The only thing I might add is a slight variation to save duplication particularly if the the contents of your paragraph tags is more complicated.
This might be better done with the following tweak on Nick's code:
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<?php
$numLoops = 2;
$ctext=""
for($i=0; $i<$numLoops; $i++) {
$info="whatever";
if($i == (numLoops-1)) {
$ctext=' class="last"';
}
echo "<p${ctext}>${info}</p>\n";
}
?>
</div>
</body>
Cheers
So you have two paragraphs, and you want to apply the class "last" to the last one? Sounds like this is better handled with CSS
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<p> first info</p>
<p> last info </p>
</div>
</body>
OR if you want to learn about loops
<?php
$numLoops = 2;
for($i=0; $i<$numLoops; $i++) {
if($i == (numLoops-1)) {
echo '<p class="last">';
} else {
echo '<p>';
}
}
What we are doing here with the for loop is initially setting the variable $i=0; then setting a test that says keep looping as long as the variable is less than the number of loops we want do do. Next we are setting what to do each loop, in this case we increment our variable by one each time.
First loop
i=0, we see that 0 is < 2 so we continue
Second loop
We execute the $i++ so we increment $i by 1 from 0 to $i=1,
we test and see $i=1 is still less than 2 so we continue.
Third attempted loop
We increment $i by 1 and get $i=2.
We test to see if this is less than 2, but it is NOT so we do not execute code in the loop
The main issue is that you don't have a loop in your code, and if you did you aren't incrementing your variable $i
Related
My count loop currently works but it is not working correctly. I need every second item to go into the right column and the rest stay in the left. So 1, 3, 5 etc in the column called split-left and 2, 4, 6 to go into the column called split-right
<!-- SPLIT EFFECT PAGE BUILDER -->
<div class="page-builder">
<?php if( have_rows('split_effect_page_builder') ): ?>
<div class="split-left">
<?php $i = 1; ?>
<?php while ( have_rows('split_effect_page_builder') ) : the_row(); ?>
<?php get_template_part('template-parts/page', 'builder'); ?>
<?php
if($i % 2 == 0){
echo '</div><div class="split-right">';
$i = 0;
}
$i++;
?>
<?php endwhile; ?>
</div>
<?php else : ?>
<?php // no layouts found ?>
<?php endif; ?>
</div>
<!-- END SPLIT EFFECT PAGE BUILDER -->
Seems you just need to reset your counter whenever it reaches 2..
<?php
if($i == 2){
echo '</div><div class="split-right">';
$i =0; // set back to zero...
}
$i++; // and now it's 1 again so next iteration would be left aligned
?>
PS.. not sure why you close a PHP tag only to immediately re-open it.. That won't break anything, but probably a good habit to get rid of.
statmentI am currently working on a project. I am having issues with making a variable ++ in the loop while nested in if statements. I really do not understand why it's doing what it's doing. Here is my code.
<?php $i=0;
while ($loop->have_posts() ) : $loop->the_post(); ?>
<?php if(get_field('featured_game') && valid_release(get_field('release_date'))):?>
<div class="item <?php if($i == 0){echo 'active';}?> row carousel-<?=$i;?>">
// do generated html
<style>
.carousel-<?=$i;?>{
// do generated css
}
</style>
</div>
<?php $i++;?>
<?php endif?>
<?php endwhile;?>
</div>
My results have
carousel-
these spots all having returned 0 despite the loop running. meaning that incrment is not happening.
if I remove the if statement the loop works, as expected. The if statement are just to verify criteria to be true. I do can place the ++ outside of the if statement I get the same results.
Could some please explain what I am missing here? This seems like such a basic problem. I really do not understand why $i will not increment when does meet the criteria and posts the correct info. Thanks in advance to anyone who takes the effort.
I ran this code:
<?php $i = 0;
while ($i < 10) : ?>
<?php if (true): ?>
<?php if ($i == 0) {
echo 'active';
} ?>
<?= $i; ?>
<?php $i++; ?>
<?php endif ?>
<?php endwhile; ?>
and the result was:
active 0 1 2 3 4 5 6 7 8 9
so either
get_field('featured_game')
or
valid_release(get_field('release_date'))
must be false.
Try
var_dump(get_field('featured_game'));
var_dump(valid_release(get_field('release_date')));
inside the loop.
Turns out, it was increment properly all along.
My issue turns out to be that bootstraps carousel cycles the the content within the the parent div not the actual div it seems. If I disable it, or look directly at the source, everything is what it is supposed to be.
I have created a newsfeed in my magento site using Zend Framework. This works almost perfectly except, I want to retrieve only the first 3 entries on the rss. If I try to do this, the first 3 items are displayed on my site but the foreach loop continues to execute so excess spaces and html elements are added in my site. How can I retrieve only the first 3 entries of the rss? Here's how my code looks:
<?php $i = 0;
<?php $channel = new Zend_Feed_Rss('http://mydomain/newsfeed'); ?>
<?php foreach ($channel as $item):
<div>
if($i<3): ?>
<label>My feed title is: <?php echo $item->title; ?>
<?php endif; $i = $i + 1; ?>
</div>
<?php endforeach; ?>
I have about 10 entries on the newsfeed so if I execute something like this, I get the first 3 properly, then I get 7 excess labels with My feed title is:. I tried, using break but this broke my entire page so I can't use that. Can someone please guide me to the right direction?
you can try with for loop instead of foreach
for($i=0; $i<=min(3, count($channel->title)); $i++) {
$feed_title = $channel->title[$i];
// do something
}
hope this will sure solve your issue.
hey guys , i know this is a stupid question but i hanged in solving it
i wrote a block of php code to show images from mysql
echo "<table><tr> ";
while($cat = $db->sql_fetchrow($catinfo)) {
echo '
<td>
<ul id="three-col" class="press">
<li>
<div class="post-content">
<a class="zoom1" href="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'">
<img src="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'" alt="artistry (via powerbooktrance)" />
</a>
</div>';
for ($i=0; $i>2; $i++) {
echo "</tr><tr>";
}
}
echo "</li></ul></td></tr></table>";
but with this code everything goes wrong and it doesnt break after each 3 images in row
i even used
if ($i>2) {
echo "</td></tr><tr>";
}
but as u know it only breaks the tr after image number 3 not every row
im really sorry for my foolish question
Try this:
echo "<table><tr> ";
$counter = 0;
while($cat = $db->sql_fetchrow($catinfo)) {
$counter++;
echo '
<td>
<ul id="three-col" class="press">
<li>
<div class="post-content">
<a class="zoom1" href="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'">
<img src="'.$galsettings[setImgDir].'/'.$cat[galCatLocation].'/'.$cat[galCatImg].'" alt="artistry (via powerbooktrance)" />
</a>
</div>
';
if ( $counter == 3 ) {
echo '</tr><tr>';
$counter = 0;
}
}
echo "</li></ul></td></tr></table>";
First off, the
for ($i=0; $i>2; $i++) {
should probably be
for ($i=0; $i < 2; $i++) {
There may be additional logic issues (looking)...
Indeed the logic seems utterly flawed, for ex. there doesn't appear to be anything which detects the the third image etc...
==> I suggest you try the snippet from tambler's answer. No point in trying and fix this one... but if you must:
the for ($i=0; $i>2; $i++) { loop is unnecessary. Even when fixed to $i < 2 (or 3...) this doesn't do anything useful.
with each new image you output a <td>, this needs to be closed with a </td>
there need to be a counter (the $i) you hint at in your snippet isn't valid
the counter is to be systematically incremented with each image
a test is to be added towards the end of the loop:
If counter >= 3 (or 2, if you make it 0-based)
reset counter;
emit ""
Also the <ul> and <li> and their respective closing tags are misplaced.
Where's you're </td> tag?
All your TDs have to be inside the TRs. You have to close the UL and TD before your TR.
So what I'm trying to do is select all the distinct months from my database and then print them in a list. That, I can accomplish. The problem lies in the fact that I need my list to be two column. The way that I achieve this with CSS is by using 2 different div's "left" and "right" which are floated next to each other. This poses a problem with PHP because it needs to echo a div close and a new div open after it echoes the sixth month. Then it needs to start again from where it left off and finish. I can't just list all of the months in the HTML, either because I don't want it to list a month if I don't have any records in the DB for that month, yet. Any ideas? I hope I was clear enough!
Thanks!
-williamg
Something like this should work (the basic idea being to just keep a count of the months an increment it as you loop through them):
<div class="left">
<?php
$x = 1;
foreach($months as $month) {
# switch to the right div on the 7th month
if ($x == 7) {
echo '</div><div class="right">';
}
echo "<div class=\"row\">{$month}</div>";
# increment x for each row
$x++;
}
</div>
<?php
$numberOfMonths = count($months);
$halfwayPoint = ceil($numberOfMonths / 2);
echo "<div class=\"left\">";
for($i=0; $i<$halfwayPoint; $i++){
echo $months[$i] . "<br />";
}
echo "</div><div class=\"right\">";
for($i=$halfwayPoint; $i<$numberOfMonths; $i++){
echo $months[$i] . "<br />";
}
echo "</div>";
?>
Rant: on
When displaying tabular data, use table instead of floating div. It will make sense when viewing the page with css disabled. If you use floated div, then you data will displayed all way down. Not all table usage is bad. People often hate table so much, so using floated div. Table only bad when used for page layout.
Rant: off
When I need to have certain content displayed with some open, close, and in-between extra character, I will make use of implode. This is the example:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
You can extends this to almost anything. Array and implode is the power that php have for many years. You will never needed any if to check if it last element, then insert the closing character, or check if it first element, then insert opening character, or print the additional character between elements.
Hope this help.
Update:
My bad for misread the main problems asked. Sorry for the rant ;)
Here is my code to make a data displayed in 2 column:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
Other solution is using CSS to format the output, so you just put the div top to down, then the css make the parent container only fit the 6 item vertically, and put the rest to the right of existing content. I don't know much about it, since it usually provided by fellow css designer or my client.
Example assumes you have an array of objects.
<div style="width:150px; float:left;">
<ul>
<?php
$c = count($categories);
$s = ($c / 3); // change 3 to the number of columns you want to have.
$i=1;
foreach($categories as $category)
{
echo '<li>' . $category->CategoryLabel . '</a></li>';
if($i != 0 && $i % $s == 0)
{
?>
</ul>
</div>
<div style="width:150px; float:left;">
<ul>
<?php
}
$i++;
}
?>
</ul>
</div>