increment a variable based on loop count - php

I have a PHP function where an undefined number of images in a directory are being output to the browser. The images are being read in to an object. The issue I'm having is how the images are presented. I want to put them in a table, four <td> cells in a row. Here is the code:
function displayThumbList(){
$tlist = $this->getThumbList();
$i = 0;
$e = 3;
echo '<table width="400px" border=1><tr>';
foreach ($tlist as $value) {
echo "<td width=\"90px\" height=\"50px\"><img class=\"timg\" src=\"thumbnail/".$value."\" alt=\"a\" /></td>";
$_GET['imagefocus'] = $this->getBaseName($value,$this->thumbPrefix);
//here is where the condition for adding a <tr> tag is evaluated
if ($i == $e){
echo '<tr>';
}
$i++; //increments by 1 with each foreach loop
}
echo '</table>';
}
The first time $i(third time through foreach loop) is equal to $e, the process adds the as expected. I need $e to increment by 3 AFTER each time the condition is met.
The number of images are undefined. If there are 21 images in the directory, $i would increment 21 times and $e should increment 7 times adding 3 with each increment (3,6,9,12,15 etc).
I guess I'm looking for an increment based on another loop condition (every time equality is reached). Any thoughts?
rwhite35

if ($i == $e){
echo '<tr>';
$e = $e + 3;
}
Alternatively, use modulo, something like
if ($i % 3 == 0)

You want to update $e when $i == $e. That condition is already being used in your if statement. Just add
$e += 3;
and you are done.
if ($i == $e){
echo '<tr>';
$e += 3;
}

Related

Reflective pattern of numbers in rows and columns of html table using loops

I'm stuck trying to use nested loops to make a reflective pattern from numbers.
I've already tried, but the output looks like this:
|0|1|2|
|0|1|2|
|0|1|2|
This is my code:
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 3; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 3; $col++) {
$p = $col-1;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>
I expected this result:
|0|1|0|
|1|2|1|
|0|1|0|
Each columns' and rows' cell values must increment to a given amount then decrement to form a mirror / palindromic sequence.
First declare the square root of the of the table cell count. In other words, if you want a 5-by-5 celled table (25 cells), declare $size = 5
Since your numbers are starting from zero, the highest integer displayed should be $size - 1 -- I'll call that $max.
I support your nested loop design and variables are appropriately named $row and $col.
Inside of those loops, you merely need to make the distinction between your "counters" as being higher or lower than half of the $max value. If it is higher than $max / 2, you subtract the "counter" (e.g. $row or $col) from $max.
By summing the two potentially adjusted "counters" and printing them within your inner loop, you generate the desired pattern (or at least the pattern I think you desire). This solution will work for $size values from 0 and higher -- have a play with my demo link.
Code: (Demo)
$size = 5;
$max = $size - 1;
echo "<table>\n";
for ($row = 0; $row < $size; ++$row) {
echo "\t<tr>";
for ($col = 0; $col < $size; ++$col) {
echo "<td>" . (($row >= $max / 2 ? $max - $row : $row) + ($col >= $max / 2 ? $max - $col : $col)) . "</td>";
}
echo "</tr>\n";
}
echo "</table>";
Output:
<table>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>2</td><td>3</td><td>4</td><td>3</td><td>2</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
</table>
There are a lot of ways to achive that.
An easy way to do that is;
<?php
$baseNumber = 0;
echo "<table border='1' style='border-collapse: collapse'>";
for ($row = 0; $row < 3; $row++) {
echo "<tr>";
if ($row % 2 !== 0) {
$baseNumber++;
} else {
$baseNumber = 0;
}
for ($col = 0; $col < 3; $col++) {
echo "<td>" . ($col % 2 === 0 ? $baseNumber : $baseNumber + 1) . "</td>";
}
echo "</tr>";
}
echo "</table>";
this code will do what you want just call the patternGenerator function with the number of distinct numbers you want for your example these numbers are 3 (0,1,2).
the idea in this code is to use two for loops one that starts from the minimum number to the maximum one and the other one that starts after the maximum number decreasing to the minimum.
for example:
if min = 0 and max = 5
the first loop will print 0,1,2,3,4,5
and the second will print 4,3,2,1,0
and that's it.
at first, I created a function that creates just on row called rowGenerator it takes $min and $max as parameters and prints one row
so if we want to print a row like this: |0|1|0| then we will call this function with min = 0 and max = 1 and
if we want to print a row like this: |1|2|1| then we will call it with min = 1 and max = 2.
function rowGenerator($min, $max)
{
echo '<tr>';
for($i = $min; $i<=$max;$i++)
echo '<td>'.$i.'</td>';
for($i = $max-1; $i>=$min;$i--)
echo '<td>'.$i.'</td>';
echo '</tr>';
}
for now, we can print each row independently. now we want to print whole the table if we look at the calls we do for the rowGenerator function it will looks as follow:
(min = 0, max = 1),
(min = 1, max = 2) and
(min = 0, max = 1).
minimums are (0,1,0).
yes, it's the same pattern again. then we need two loops again one to start from 0 and increase the number until reach 1 and the other one to loop from 0 to 0.
and that's what happened in the patternGenerator function. when you call it with the number of distinct numbers the function just get the min that will always be 0 in your case and the max.
function patternGenerator($numberOfDistinct )
{
echo "<table border =\"1\" style='border-collapse: collapse'>";
$min = 0;
$max = $numberOfDistinct - 2;
for($i = $min;$i<=$max; $i++)
{
rowGenerator($i,$i+1);
}
for($i = $max-1;$i>=$min;$i--)
{
rowGenerator($i,$i+1);
}
echo '</table>';
}
this is the output of calling patternGenerator(3):
the output of calling patternGenerator(5):

PHP For loop, Print specifc no of times

I want to loop and echo images specific value, I have a db value e.g 100, but i want to echo only 96 images only not more than that. Also whatever the value from DB and loop should print the exact times not exceeding 96(which is fixed)
$check = "SELECT white FROM balloons";
$rs = mysqli_query($con,$check);
if(mysqli_num_rows($rs)==1)
{
$row = mysqli_fetch_assoc($rs);
$g=$row['white']; //eg 2,
for($imagecount=0;$imagecount>$g;$imagecount++) {
echo '<img src="img/whiteB.png" class="w_over" />';
}
}
for ($i=0; $i < min($g, 96); $i++) {
echo '<img src="img/whiteB.png" class="w_over" />';
}
I'd change
for($imagecount=0;$imagecount>$g;$imagecount++) {
to
for($imagecount=0;$imagecount<=min($g,96);$imagecount++) {
Pls. note that the 2nd param in for needs to inverted (loop while condition is true)
If i get your question correctly you just need to change your line,
$g=$row['white'];
to:
$g = ($row['white'] < 96) ? $row['white'] : 96;
Side Note:
for($imagecount = 0; $imagecount < $g; $imagecount++) //Should be less then
^
Error in for loop condition!
change for loop head:
for($imagecount=0;$imagecount<$g;$imagecount++)

Insert line break after every two rows of database

I have a little script that prints a certain amount of rows in a mysql database.
Is there any way to make it so that after every second row it prints, there is a line break inserted?
Adding a line break after every row is simple, but I don't know how to add one after every other row. Is that possible?
You write "script" but in tags you have PHP, so I suppose you need PHP code:
foreach ($rows as $row) {
if ($i++ % 2) {
// this code will only run for every even row
}
...
}
$i=1;
while ($row = mysql_fetch_array($query))
{
//your code
if ($i % 2 == 0)
echo '<br>';
$i++;
}
add new variable before the loop
$i = 0;
then in your loop add
if ($i != 0 && $i%2 == 0)
echo '<br/>';
Depending on the language, something like this should do it: (in php) (where $arr is an array of results)
$str = '';
$i = 0;
for ($i=0; $i<count( $arr ); $i++)
{
if ( ( $i + 1 ) % 2 === 0 )
{
$str .= $arr[$i] . '<br />';
}
else
{
$str .= $arr[$i];
}
}
echo $str;
Use php and modulo.
such as
if($i % 3)
{
echo '<br />'..
If you need to do this inside the query for some reason, you could use something like
SELECT
<your fields>,
IF (((#rn:=#rn+1) % 3)=0,'<br>','') as brornot
FROM
<your tables and joins>,
(#rn:=0)

Dynamic Table Layout using PHP Logic

I have simple table that has about 80 rows, which I populate dynamically using PHP. What I am trying to do is to layout those rows in chunks for each column. So if I have 80 rows, I would like 4 columns of 20 rows or so, maybe the last column has less or more depending on the total number of rows. The total number of rows can change!
I am having trouble coming up with an implementation method that will not get messy! Anyone know of a simple way that I can implement this.
I have tried using a counter as I loop the data to populate the table and when a multiple of of 20 is reached move to the next block but that didn't work for me as I had extra rows left over.
foreach($indexes as $index){
$counter++;
echo '<tr>';
if($counter > 20){
$multiplier = $counter / 20;
$head = '<td></td>';
for($i=1; $i<$multiplier; $i++){
$head .= '<td></td>';
}
}
if($counter < 20){
$head = '';
}
echo "$head<td>$index</td><td><input id='$index' name='$index' type='checkbox' /></td>";
echo '</tr>';
}
Thanks all for any help
I would do :
$nbCols = 4;
$nbRows = count($indexes)/$nbCols;
for($row=0; $row<$nbRows; $row++) {
echo "<tr>";
for($i=0; $i<$nbCols; $i++) {
$index = $indexes[$row + ($i*$nbRows)];
echo "<td>$index</td><td><input id='$index' name='$index' type='checkbox' /></td>";
}
echo "</tr>";
}
Wouldn't you want to see the remainder of your division and deal with that also?
if($counter % 20 == 0){
// You've no remainder
}else{
// Do another loop to output the odd rows
}
Or you could % 2 == 0 to see if it's even, and then just multiply the whole result by 10.
Be sure to look at ceil() and floor() also for ensuring your number of rows is a round number.
if you dont mind to have this kind of cell order:
1 2 3 4
5 6 7 8
you can use <div style='float:left'>$cellValue</div> in the loop without use of table.

PHP Loop do some once the loop as finished

I have this PHP loop,
foreach($returnedContent as $k => $v) {
$imageName = str_replace($replaceData, "", $v['contentImageName']);
echo "<a class='contentLink' href='".base_url()."welcome/getFullContent/$v[contentId]'>";
echo "<img src='/media/uploads/".strtolower($v['categoryTitle'])."/".$imageName."_thumb.png' alt='$v[contentTitle]' />";
echo "</a>";
}
Once the lopp has finished I was hoping it would be possible to do loop to print x amount of grey boxes is this possible and if so how, basically if the first loop returns 1 item i need the second loop to print out 11 boxes, if the first one returns 9 items I need the second loop to return 3 boxes.
Make sense? Can anyone help me?
So if you want a total of 12 boxes, set a counter and decrement:
$boxes = 12;
foreach($returnedContent as $k =>$v){
// all your previous stuff
$boxes--;
}
for($i = 0; $i < $boxes; $i++){
// print your box here
}
Depending on your application you may also want to check that the number of items in $returnContent is <= $boxes. If it is greater than $boxes you won't get an error but you will get rows with more than $boxes images.
Just keep a counter and increment it for each loop iteration, then add
for (;$counter < 11; ++$counter) {
do_loop_stuff();
}
Maybe you could do something like this (assuming $returnedContent is numerically indexed):
//count to 12 so we get 12 items
for ($i=0; $i<12; $i++) {
//check if there is an entry to print
if (isset($returnedContent[$i])) {
$v = $returnedContent[$i];
$imageName = str_replace($replaceData, "", $v['contentImageName']);
echo "<a class='contentLink' href='".base_url()."welcome/getFullContent/$v[contentId]'>";
echo "<img src='/media/uploads/".strtolower($v['categoryTitle'])."/".$imageName."_thumb.png' alt='$v[contentTitle]' />";
echo "</a>";
} else {
//draw grey box
}
}
After the first loop, you can do:
for($i = 0; $i < 12 - count($returnedContent); $i++)
{
// print the grey boxes.
}
Hmmm Im not sure Im understanding you but
$c = count($returnedContent);
will get you the amount of items in the variable
then:
$c = (11-$c);
if($c > 0) {
for($i=0;$i<$c;$i++) {
// print gray box
}
}
after the first loop. You could also use a counter variable inside the first loop.
I did interpret the question as "Do something when the loop has finished iterating".
In which case a for/foreach loop isn't the best choice here.
how about
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
//then do whatever else you need to.
?>

Categories