Blankline after foreach loops - php

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

Related

php foreach wrap every 2 divs

I need to wrap every 2 divs with another div for a project (a row) so it will look like:
<div class="row">
<div> Item </div>
<div> Item </div>
</div>
<div class="row">
<div> Item </div>
<div> Item </div>
</div>
I have tried a few solutions but they dont work since the items coming in are odd (9 items). Here is what I had:
<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];
++$count;
if($count == 1)
{
echo "<div class='et_pb_row'>";
}
foreach ($books as $book)
{
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>
<?php
}
if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
?>
This works except the second to last row has 3 items even though it dispays the "count" as 2 when I echo it out so it should reset but doesnt. So its:
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
You should open and close your <rows/> in the books loop, and add a late check for odd books:
<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];
foreach ($books as $book)
{
++$count;
if($count == 1)
{
echo "<div class='et_pb_row'>";
}
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>
<?php
if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
}
if ($count > 0)
{
echo "</div>";
}
?>
Doing so, your $count variable will be incremented only when foreach($books AS $book) loop is run (thus you have at least one book to print)
You can take advantage of array_chunk :
//First make a generator to get all books
function allBooks($contents) {
foreach($contents as $content) {
foreach($content['tags'] as $book) {
yield $book; //Here you can yield whatever you want !
}
}
}
//Then create rows
$itemPerRow = 2;
$rows = array_chunk(iterator_to_array(allBooks($contents)), $itemPerRow, true);
//Display all
foreach($rows as $row) {
echo '<row>';
foreach($row as $book) {
//Display the book !
}
echo '</row>';
}

Remove comma on last item of foreach

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

Endforeach loop different class for first item

I'm not that good at php. What i have is a list of items looped with endforeach. What I want is that the first loop will have a class of col-lg-12 and from the second one that class will become col-lg-6. How can I achive that?
Here's the code:
<?php $firstLoop = true;
foreach( $network_value as $key => $value ){
if( $firstLoop ){
echo '<div class="col-lg-12">';
}
echo '<div class="col-lg-6">';
$firstLoop = false;
} ?>
^This is the code that I've tried, but it's not working how i wanted.
<?php if ($img): ?>
<img src="<?php echo $thumb->src ?>" width="<?php echo $thumb->width ?>" height="<?php echo $thumb->height ?>" alt="" />
<?php endif; ?>
<h4>
<div class="circle"><?php echo $datePublic = date('d M', strtotime($page->getCollectionDatePublic())); ?></div>
<br>
<a class="blogTitle" href="<?php echo $url ?>" target="<?php echo $target ?>"><?php echo $title ?></a></h4>
<h6>Posted by <?php echo $author; ?></h6>
<br>
<p><?php echo $description ?></p>
</div>
<?php endforeach; ?>
The most simple way to do it is to add a counter and check if it is the first value in the counter.
<?php
$counter = 0;
foreach( $network_value as $key => $value )
{
if($counter == 0){
echo '<div class="col-lg-12">';
} else {
echo '<div class="col-lg-6">';
}
$counter++;
}
?>
Also I want to add that there are two ways of using foreach and if-statements, but you are trying to mix them, which is wrong.
The first method is using brackets "{" and "}":
foreach($users as $user) {
// do things for each user
echo $user->name; // Example of writing out users name
}
And if-statement:
if(true) {
// do something
}
The second method is using "foreach(statement):" and "endforeach;"
foreach($users as $user):
// do things for each user
echo $user->name; // Example of writing out users name
endforeach;
And if-statement:
if(true):
// do something
endif;
Edited:
In your case you can use:
<?php
foreach ($pages as $key=>$page):
if($key==0){
echo '<div class="col-lg-12">';
} if($key==1){
echo '<div class="col-lg-6">';
}
endforeach; ?>
Or you can use:
<?php
foreach ($pages as $key=>$page):
if($key==0){
echo '<div class="col-lg-12">';
} else {
echo '<div class="col-lg-6">';
}
endforeach; ?>
OLD:
foreach($array as $key=>$row){
if($key==0){
echo '<div class="col-lg-12"></div>';
}
if($key==5){
echo '<div class="col-lg-6"></div>';
}
// OR try use %
if($key%2 == 0){
echo '<div class="col-lg-12"></div>';
} else {
echo '<div class="col-lg-12"></div>';
}

If statement to not show div / h2

This for each / if statement displays changes, and then right below it it displays the changes made.
I am trying to write an if statement that tells it not to show the h2 and the #change_box if there are no changes.
Help would be greatly appreciated.
<h2 class="changes"> Changes: </h2>
<div id="change_box">
<? foreach ($audit['Events'] as $event):?>
<?if ( $event['Type'] != 'Comment'):?>
<span class="field">
<?= $event['Field']?>
</span>:
<?= $event['Value'] ?>
<?=($event['Previous'])?>
<?endif?>
<?endforeach?>
</div>
<?php
if ($changes) { // You'll have to set this variable
//Echo all of your HTML
else {
//Echo the stuff you'd rather show if they didn't change anything
}
?>
To give you an idea of how I'd write your code
<?php
if ($changes) {
echo '<h2 class="changes">Changes:</h2>';
echo '<div id="change_box">';
foreach ($audit['Events'] as $event) {
if ($event['Type'] != 'Comment') {
echo $event['Field'] . </span> . $event['Value'] . $event['Previous'];
}
}
echo "</div>"
}
?>
You could wrap your code with an if like
if(count($audit['Events'])>0)
{
//Your code
}
Wny do you open and close php tags every time? Would be better to make everything in PHP and echo whenever you want to print HTML code.
<?php
echo "<h2 class=\"changes\"> Changes: </h2>";
echo "<div id=\"change_box\">";
foreach ($audit['Events'] as $event) {
if ( $event['Type'] != 'Comment') {
echo "<span class=\"field\">".$event['Field']."</span>";
echo $event['Value'];
echo "(".$event['Previous'] .")";
}
}
echo "</div>";
?>
please make space after each <? and make sure you enabled short tags
<?php if(is_array($audit['Events']) && $audit['Events']):?>
<h2 class="changes"> Changes: </h2>
<div id="change_box">
<?php foreach ($audit['Events'] as $event):?>
<?php if ( $event['Type'] != 'Comment'):?>
<span class="field">
<?php echo $event['Field'];?>
</span>:
<?php echo $event['Value']; ?>
<?php echo $event['Previous'];?>
<?php endif;?>
<?php endforeach;endif;?>
</div>

How to perform a count in a loop

foreach ($arrQuestionId as $key=>$question) {
?>
<div class='lt-container'>
<p><strong>QUESTION <span id="quesnum"></span>:</strong></p>
</div>
<?php
}
?>
In code above I have a while loop where it displays QUESTION :. Now what I want to do is in between QUESTION and : I want to include a count number so that for every time QUESTION appears, it contains a count number next to it as like below:
QUESTION 1:
QUESTION 2:
QUESTION 3:
...
How can this be done?
Create a variable and increment it in foreach.
Like:
$s = 1;
foreach($value as $text) {
echo "Question #".$s." :".$text;
$s++;
}
Take a variable and increment it
$i=1;
foreach ($arrQuestionId as $key=>$question) {
?>
<div class='lt-container'>
<p><strong>QUESTION <span id="quesnum"><? echo $i; ?></span>:</strong></p>
</div>
<?php
$i++;
}
?>
$count = 1;
foreach ($arrQuestionId as $key=>$question) {
?>
<div class='lt-container'>
<p><strong>QUESTION <span id="quesnum"><?php echo $count++; $></span>:</strong></p>
</div>
<?php
}
?>
$i=0;
foreach ($arrQuestionId as $key=>$question) {
$i=$i+1;
?>
<div class='lt-container'>
<p><strong>QUESTION <span id="quesnum"></span>:<?php echo $i;?></strong></p>
</div>
You can try the following way too,
$countArray = array();
foreach ($arrQuestionId as $key=>$question) {
$countArray[] = $key;
}
count($countArray) or sizeOf()
(OR) Directly you can get without for loop itself like the below
count($arrQuestionId)
$qno = 1;
foreach ($arrQuestionId as $key=>$question) {
?>
<div class='lt-container'>
<p><strong>QUESTION <span id="quesnum"></span>:</strong><?php echo $qno?></p>
</div>
<?php
$qno++;
}
?>

Categories