PHP: wrapping each group of 3 elements - php

I am trying to figure out how to write a loop that will wrap every group of 3 elements. However, for the last iteration, it should wrap whatever is left (be it one, two or three elements)
So basically this kind of pattern:
div
do stuff
do stuff
do stuff
end-div
div
do stuff
do stuff
do stuff
end-div
div
do stuff
do stuff
do stuff
end-div
div
do stuff
end-div
Here is where I'm at so far:
<?php
$counter = 0;
for ($i = 1; $i <= 10; $i++) {
if (($counter + 1) % 3 == 0) {
echo 'div <br />';
}
echo 'do stuff <br />';
if (($counter + 1) % 3 == 0) {
echo 'end-div <br />';
}
$counter ++;
}
?>
This is giving me the following:
do stuff
do stuff
div
do stuff
end-div
do stuff
do stuff
div
do stuff
end-div
do stuff
do stuff
div
do stuff
end-div
do stuff
Can anyone see where I'm going wrong?

In other words, you need to write div before each group of three items and end-div after each group of three items:
// $counter always tells the number of processed items
$counter = 0;
for ($i = 1; $i <= 10; $i++) {
// before a group of three, $counter is a multiple of three
if ($counter % 3 == 0) {
echo 'div <br />';
}
// process the item then count it
echo 'do stuff <br />';
$counter ++;
// after a group of three, $counter is a multiple of three
if ($counter % 3 == 0) {
echo 'end-div <br />';
}
}
// close the last group if it is not complete
if ($counter % 3 != 0) {
echo 'end-div <br />';
}
Check it online.

There's no need to use separate $counter variable, make use of $i variable in the for loop itself.
echo 'div <br />';
for ($i = 0; $i < 10; $i++) {
if($i != 0 && $i % 3 == 0)
echo 'end-div <br /> div <br />';
echo 'do stuff <br />';
}
echo 'end-div';

This is how I solved the problem
$total_items = 11;
for( $i = 0; $i < $total_items; $i ++ ){
// get the starting element
// the starting element will have ($i + 1 ) % 3 = 1
// all starting elements in the group will have a modulus of 1 when divided by 3
if( ( $i + 1 ) % 3 == 1 ){
echo "div <br />";
}
echo "do stuff <br />";
// the group will either end where ($i + 1 ) % 3 = 0
// or at the end of the count
// if total items are 2 then it will end at 2
if( ( $i + 1 ) % 3 == 0 || ( $i + 1 ) == $total_items ){
echo "end-div <br /><br />";
}
}
I ran my code using w3schools PHP compiler, please see the screenshot

Related

php each 1 and 8 element in 2 iterations

I have a loop. I need write to 1 and 8 element a button. How I can do it?
$cnt = 1;
while($r = $now->fetch_assoc()) {
if ($cnt > 6) {
break; //write only 5 elements to 1 iteration
}
if($cnt === 1 || $cnt === 8) { //not working
echo "<button>Send</button>";
}
$cnt++;
}
My condition is now working. How I can do correctly condition to 8 element, which in 2 iterations?
Example, waht I want get:
------Button-------
1) record
2) record
3) record
4) record
5) record
1) record
2) record
3) record
------Button-------
1) record
2) record
....
Maybe I understand your question wrong, but I think that this should achieve it.
$i = 1;
$j = 1;
while($r = $now->fetch_assoc()) {
if ($i > 6) {
$i = 0;
}
if($j === 1 || $j%8 === 0) {
echo "<button>Send</button>";
}
$i++;
$j++;
}

limit pages shown in pagination php script

I have 100+ records in my database so i am using pagination but it prints page number for every page like 1,2,3,5 and so on how to limit the number shown in pagination.
Here is my code:
$row_offer2=mysqli_num_rows($sql_result2);
$total=ceil($row_offer2/$num_rec);
echo "<div class='col-md-12' style='margin:0 auto;text-align:center;'><ul
class='pagination '>";
echo "<li id='1' class='pag'>".'|<'."</li>"; // Goto 1st page
for ($i=1; $i<=$total; $i++) {
echo "<li id=".$i." class='pag'>".$i."</a></li> ";
};
echo "<li id=".$total." class='pag'>".'>|'."</a></li> "; // Goto last page
echo "</ul></div>";
?>
Show pagination for current page +- x pages (x should be something like 2-3) and show the first and last page.
$currentPage = 6;
function getPages($cp, $max, $offset) {
$pages = [];
$pages[] = 1;
$min = ($cp - $offset) > 1 ? $cp - $offset : 1;
$lim = ($cp + $offset) < $max ? $cp + $offset : $max;
for ($i = $min; $i < $lim; $i++) {
$pages[] = $i;
}
$pages[] = $max;
return array_unique($pages);
}
var_dump(getPages($currentPage, 20, 3));
then you can simply loop with foreach through array you receive from this function and display your LIs
Control your loop with number you want to show. If you want to show 3 pages in pagination just do this.
for ($i=1; $i<=3; $i++) {
echo "<li id=".$i." class='pag'>".$i."</a></li> ";
};

How to break foreach loop or for loop into 10 records

Suppose I have 56 records in my database. I'm using a FOR LOOP to display them.
I want to append div after 10 records every time.
<?php
$a = 56;
for($i=0;$i<$a;$i++){
echo "<div>";
echo $i."</br>";
echo "</div>";
}
?>
output:
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
...
<div>56</div>
I want to append <div> after 10 records each time
<div>
0
1
2
.
9
</div>
<div>
10
11
.
19
</div>
.
.
<div>
51
52
.
.
56
</div>
You can use the modulus operator for that.
<?php
$a = 56;
echo "<div>";
for($i=0;$i<$a;$i++){
echo $i . "<br />";
if (($i+1) % 10 == 0) {
echo "</div><div>";
}
}
echo "</div>";
?>
Note that if the number of loops is unknown - it's possible that $a will be 9, and your output will be:
<div>
0
...
9
</div><div>
</div>
If you want to prevent the duplicate of the close-open div in case of exact division, you can change your code to:
<?php
$a = 56;
echo "<div>";
for($i=0;$i<$a;$i++){
echo $i . "<br />";
if (($i+1) != $a && ($i+1) % 10 == 0) {
echo "</div><div>";
}
}
echo "</div>";
?>
You need to append the opening and the closing divs based on some condition which primarily are
If it is the first iteration
If it is the tenth iteration
If it is the last iteration
Here is a sample code:
$a = 56;
for ($i = 0; $i < $a; $i++) {
// If it is the first iteration, echo a opening div
if ($i == 0)
echo "<div>";
// If it is a tenth iteration but not the last one then append a closing and a opening div
if ($i != 0 && $i % 10 == 0 && $i != $a - 1)
echo "</div><div>";
echo $i.
"<br>";
// If it is the last iteration, append a closing div
if ($i == $a - 1)
echo "</div>";
}

PHP Loop determine 4th iteration but if the iteration is less than 4 echo something

Heres the scenario, I have array with 7 items and I want to separate them in every fourth iteration.. just like this
$counter2 = 0;
$counter3 = 0;
$counter4 = 0;
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0)
{
echo $sample_array_value;
}
elseif(++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
}
The out put will be div AsoPusaDagaKuting /div div TutaBubwitBoom
The problem is when it ends in iteration that doesn't count 4 it doesn't give the separator ending..
I need it to output div AsoPusaDagaKuting /div div TutaBubwitBoom /div
Thanks in advance...
You can split it with array_chunk, implode the new subarrays of 4 with array_map, then echo it with implode.
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
echo "<div>", implode("</div><div>", array_map("implode", array_chunk($sample_array, 4))), "</div>";
Result:
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
Try this:
$i = 0;
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0 || ++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
$i++;
}
if ($i % 4 != 0) {
echo "</div>";
}
You are printing the values inside every condition, then why not use echo once outside any condition? Also you want to close and open a div tag for the forth element, then only 1 counter would do the trick. Only this will work -
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
$i = 0;
echo "<div>";
foreach($sample_array as $sample_array_value)
{
if($i > 0 && $i % 4 == 0)
{
echo "</div><div>";
}
echo $sample_array_value;
$i++;
}
echo "</div>";
Output
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>

Random number of divs with random number of elements with PHP

I need to generate random number of divs with five items per div (and remaining items in the last div) from random number of $totalItems and also not all the items satisfy $OKItems... Hopefully the code explains better than me.
My problem is that this script generates empty divs with no content in them.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br />' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
echo ($OKItems % 5 == 0 || $i+1 == $totalItems) ? '<br />div close<br />' : '';
}
?>
This is what I might get:
div open
div close
div open
11111
div close
div open
div close
div open
div close
div open
11
div close
And this is what I would have wanted in this case:
div open
11111
div close
div open
11
div close
<?php
const N = 5;
$totalItems = rand(2,30);
$items = array() ;
for ($i = 0; $i < $totalItems; $i++) {
$testValue = rand(0, 1);
if ($testValue != 0) {
$items[] = 1 ;
}
if( N == sizeof($items) || (($i == $totalItems - 1) && 0 < sizeof($items)) ) {
echo "<div>" . join(",", $items) . "</div>";
$items = array() ;
}
}
I think you need a bit more structure to your code.
My approach would be to break it up into several stages, as opposed to trying to do all the logic in the loop that outputs data.
What I'd suggest:
Decide how many items to be tested
Test each item and only copy the ones that pass into a new array
Partition this new array into sets of 5
Output each partition as a div
Code (untested):
// Decide how many items to test
$totalItems = rand(2,30);
// Test these items and add them to an accepted array
$items = Array();
for ($i = 0; $i < $totalItems; $i++) {
$testValue = rand(0, 1);
if ($testValue != 0) { $items[] = "1" }
}
//Partition them into sections
$partitions = array_chunk($items,5);
//Output as divs
foreach($partitions as $partition):
echo 'div open <br />';
foreach($partition as $item):
echo $item . "<br />";
endforeach;
echo 'div close <br />';
endforeach;
When you split up the code into logical steps, it becomes much easier to maintain and debug.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br>' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
if($OKItems % 5 == 0 || $i+1 == $totalItems) {
echo '<br>div close<br>';
$OKItems = 0;
}
}
?>
That should be working ;)
I changed your check line for an if function that also resets your $OKItems. The problem you had (i think) was that you got a 0 as the random value and that would keep $OKitems on 5.

Categories