How to perform a count in a loop - php

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

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

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

Foreach loop, offset or skip first post in the loop

I'm trying to figure this out for hours but I can't. I just want to show the second post and skip the first one, just like the Wordpress offset function. I'm using AW blog extension for Magento and I want to skip the first post in the recent blog posts. Below is my modified code showing one post recent post in a homepage block. I just want to create another block that will show the second recent post. :(
<?php $posts = $this->getPosts(); ?>
<div id="messages_product_view">
<?php Mage::app()->getLayout()->getMessagesBlock()-> setMessages(Mage::getSingleton('customer/session')->getMessages(true)); ?>
<?php echo Mage::app()->getLayout()->getMessagesBlock()->getGroupedHtml(); ?>
</div>
<?php
foreach ($posts as $post):
if ($i++ >= 1) break;
?>
<div class="postWrapper">
<div class="postTitle">
<h3><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h3>
</div>
<div class="postContent"><?php echo $post->getPostContent(); ?></div>
</div>
<?php endforeach; ?>
I will recommend you to check the count and after printing it stop the loop, otherwise it will loop the entire array to the end and print just the second iteration.
$i=0;
foreach ($posts as $post){
if ($i==1) {
//print your div here
$i++; //added here after edit.
continue;
}else if ( $i>1 ){
break;
}
$i++;
}
This way it will only iterate twice.
Try changing:
foreach ($posts as $post):
if ($i++ >= 1) break;
to:
//set $i outside of loop
$i=0;
foreach ($posts as $post):
if ($i==0) {
$i++;
//skip the first record
continue;
}
Try this -
<?php $i=1;
foreach ($posts as $post):
if ($i > 1) {
?>
<div class="postWrapper">
<div class="postTitle">
<h3><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h3>
</div>
<div class="postContent"><?php echo $post->getPostContent(); ?></div>
</div>
<?php }
$i++;
endforeach; ?>

Echo array value in different sections

I want to echo a value of an array in a way that the first 4 would echo in a section and the rest (can be 5 or more) in a different section. For example:
<?php $items = $kStore->getItems(); ?>
<div id="section1">
<?php foreach($items as $item) {
if($count <= 4){
?>
<h1><?php echo $item->getId(); ?></h1>
<?php } }?>
</div>
<div id="section2">
<?php foreach($items as $item) {
if($count > 4){
?>
<h1><?php echo $item->getId(); ?></h1>
<?php } } ?>
</div>
I imagine it has to be something 'like that' but dont know how to get the count. Also, I don't want to go through the array twice, I feel it's not the fastest way to do it. Any thoughts? Thanks!
You can use array_slice to offset the start and limit the length of the section of the array you iterate over:
<div id="section1">
<?php foreach(array_slice($items, 0, 4) as $item) { … } ?>
</div>
<div id="section2">
<?php foreach(array_slice($items, 4) as $item) { … } ?>
</div>
Update
If $items is not an array, but merely a non-array object that implements Iterator, you can't use this approach, but you can probably use LimitIterator instead.
<?php
$sectionOneItems = new LimitIterator($items, 0, 4);
$sectionTwoItems = new LimitIterator($items, 4);
?>
<div id="section1">
<?php foreach($sectionOneItems as $item) { … } ?>
</div>
<div id="section2">
<?php foreach($sectionTwoItems as $item) { … } ?>
</div>
If this, too, does not work, then some more introspection of the object being iterated over is required.
i think this function might be useful for you
array_chunk ().http://www.php.net/manual/en/function.array-chunk.php

Display second value from mysql by foreach loop

Sorry, If my question is not good.
I am using this code to display values from mysql database.
<?php foreach ($values as $value) { ?>
<span><?php echo cimy_uef_sanitize_content($value['VALUE']); ?></span>
<?php } ?>
It is displaying result like this
-> http://pkbazaar.com/realoffers/wp-content/Cimy_User_Extra_Fields/riaz/avatar/aget-3.png
-> Johar Town
-> 1234567
-> 54000
-> Australia
-> WA
-> Lahore
But I don't want to display first value like "http://localhost/realoffers/wp-content/Cimy_User_Extra_Fields/riaz/avatar/aget-3.png"
What I should do to start displaying value from second value like "Johar Town".
If you don't need the first value you can shift the element off the beggining of array.
<?php $old_value = array_shift($values); ?>
<?php foreach ($values as $value) : ?>
<span>
<?php echo cimy_uef_sanitize_content($value['VALUE']); ?>
</span>
<?php endforeach; ?>
<?php $count = 0;
foreach ($values as $value) {
if($count == 0 ) {
$count++;
} else { ?>
<span><?php echo cimy_uef_sanitize_content($value['VALUE']); ?></span>
<?php }
} ?>
Try this:
<?php
foreach ($values as $k=>$value) {
if ($k==1){
?><span><?php echo cimy_uef_sanitize_content($value['VALUE']); ?></span><?php
}
}
?>
If the number of records is the same in each array and a fixed value, it would be fairly simple to use the following:
<?php
foreach ($values as $value)
{
?>
<span><?php echo cimy_uef_sanitize_content($value['FIELD2']); ?></span>
<span><?php echo cimy_uef_sanitize_content($value['FIELD3']); ?></span>
<span><?php echo cimy_uef_sanitize_content($value['FIELD4']); ?></span>
<span><?php echo cimy_uef_sanitize_content($value['FIELD5']); ?></span>
<span><?php echo cimy_uef_sanitize_content($value['FIELD6']); ?></span>
<?php
}
?>
It's probably better to change your query to not return a row you don't need but you can just remove the first item from the array:
<?php
array_shift($values);
foreach ($values as $value) { ?>
<span><?php echo cimy_uef_sanitize_content($value['VALUE']); ?></span>
<?php } ?>
See http://uk1.php.net/array_shift
<?php
unset($values[0]);
foreach ($values as $value) { ?>
<span><?php echo cimy_uef_sanitize_content($value['VALUE']); ?></span>
<?php } ?>
If you want to exclude url pattern than you should use regex match like this:-
<?php
foreach ($values as $value)
{
if(!preg_match('#^(http|https)?://#', $value))
{
?>
<span><?php echo cimy_uef_sanitize_content($value['VALUE']); ?></span>
<?php
}
}
?>
Hope this will help you to exclude urls.

Categories