Controlling for-loop output - php

Is it possible to control a for-loop when it reaches a certain condition?
Explanation:
I'm retrieving the folder path to a collection of images from a database: these images are then printed out via a for-loop. What I would need to do is control how these images are displayed on the page (say, 5 images per row).
As of now, the for-loop prints out 40 images in a single row, which makes you scroll to the furthest right of the page.
Is there a solution for controlling the for-loop, as in for instance, after 5 successful loops, echo out a < br >? Here's a vulgar thought:
for ($i = 1; $i < $rows; $i++) {
$path = $image[$i];
$folder_path = $path['folder_path']; //since it's an array
echo '<img src="' . $folder_path . '">';
//pseudocode
if ($i == 5) {
echo '<br>';
...continue with the loop
}
}
I know the pseudocode looks crazy, but that's pretty much what I need to do: loop for x amount of instances, add something, then continue.

As per #m69's comment, the best option would be to use the % (modulus) comparison operator. As explained by the PHP docs:
$a % $b returns the remainder of $a divided by $b.
So, in your case:
for ($i = 0; $i < $rows; $i++) {
$path = $image[$i];
$folder_path = $path['folder_path']; //since it's an array
echo '<img src="' . $folder_path . '">';
if ($i % 5 == 0) { //do this if $i divided by 5 has a remainder of 0
echo '<br>';
}
}
As a side note, you should set $i to 0 at the beginning of your for loop, assuming $rows is set to the number of rows returned from your query. Setting it to 1 will keep it from iterating through the last row, because $i will == 40 (assuming 40 rows), and so will NOT be < 40.

The same loop. The condition for inserting the is ($i % 5 == 0), which means (if this element is the fifth one of his series) will be useful for you.
<?php
for ($i = 1; $i < $rows; $i++) {
$path = $image[$i];
$folder_path = $path['folder_path'];
echo '<img src="' . $folder_path . '">';
if ($i % 5 == 0) {
echo '<br>';
}
}

Related

Exam Qn: Convert do while loop to for loop (PHP)

Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:
"Convert the following script using for loop without affecting the output:-"
<?php
//Convert into for loop
$x = 0;
$count = 10;
do
{
echo ($count. "<BR>");
$count = $count - 2;
$x = $x + $count;
}
while($count < 1)
echo ($x);
?>
Please help me as my computer sir is out of station and I am really puzzled by it.
Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.
Try:
$count = 10;
$x = 0;
$firstRun = true;
for(; $count > 1 || $firstRun;) {
$firstRun = false;
echo ($count . "<BR>");
$count -= 2;
$x = $x + $count;
}
echo ($x);
By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.
EDIT
$firstRun to avoid infiniteLoop
$count in loop
EDIT
Fixed code for new requirement
Removed unnecessary code
Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1.
The output of your teacher's code is:
10
8
I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output:
10
8
6
4
2
20
Then a good for() loop would have been :
$x = 0;
$count = 10;
for($i = $count; $i > 1; $i -= 2)
{
$count -= 2;
echo $i . "<br>";
$x += $count;
}
echo $x;
Which will output the same values.
If you can, ask your teacher for this, and comment the answer ^^ ahahah

PHP even numbers generating

I'm somewhat new to PHP, been reading a few books and I've never seen a loop where it gets you all the even numbers(for example from 1 to 10), so I decided to try it myself:
for($i=0;$i<10 && $i % 2===0;$i++)
echo $i;
Tried with only double == as well.
And this,
$i=0;
do echo $i; while($i++<10 && $i % 2 ==0);
Can't seem to figure out how to use 2 conditions in the same statement.
Would appreciate the help!
Thanks.
Try to use this code
for( $i=0; $i<=10; $i++ )
{
if( $i%2 == 0 ){
echo $i;
}
}
The loop is breaking entirely when the second condition fails the first time. On the first iteration: 0 is less than 10, and it is even, so the loop iterates. On the second iteration: 1 is less than 10, but is odd, so the loop breaks.
Your code is the equivalent of this:
for($i=0; $i<10; $i++) {
if ($i % 2 !==0 ) {
break;
}
echo $i;
}
0
You can eliminate the second condition of your for loop to prevent the breakage and rely exclusive on a third expression to increment $i by two each iteration.
for($i=0; $i<10; $i = $i + 2) {
echo $i;
}
02468
The second statement in a for-loop is/are the condition(s) which gets checked every loop. so if it fails your loop stops. what you need will look somewhat like this:
for ($i = 0; $i < 10; $i++)
if ($i % 2 == 0)
echo $i;
So the loop will run over every number but only print out the even ones.
You don't need to loop.
Range can create a range with third parameter step 2.
$arr = range(0,20,2);
Echo implode(" ", $arr);
https://3v4l.org/S3JWV
you can use also regular loop and get the evens by formula:
for($i=0; $i<10 ;$i++) {
$j = $i * 2;
// do somthing with $j witch loop over 10 first evens...
}

PHP Explode function. If function

Could someone help suggest in below php explode function, we are displaying script after 5th listing. How is it possible to display script exactly after 5th listing and 10th listing on a page which has more than 10 listings
We tried using
if ($i == 5 & $i== 10)
but it does not work
Below is original code - which displays script after 5th listing
<?php
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 0; $i < $numberOfListings; ++$i)
{
if ($i == 5)
{ ?>
<script> </script>
<?php }
echo $listings[$i] . "<hr/>";
}
?>
Edit
How is it like - if have to display a separate script on $i==9, could you advise.
Because $i starts at 0 (0 to 9 is 10, whilst 0 to 10 is 11). Try if ($i == 4 || $i== 9), with an or operator.
Also I would not use the && (the and operator), because it is unlikely $i will ever equal both 4 and 9. I'd suggest you read into Truth Tables (and maybe Propositional Calculus) because from seeing what you had tried originally, it would be helpful to understand how a truth table works.
(source: wlc.edu)
You can use the contine, continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
$arr = range(0,9);
foreach($arr as $number) {
if($number < 5) {
continue;
}
print $number;
}
Ref: http://php.net/manual/en/control-structures.continue.php
Try using modulus operator
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 1; $i < $numberOfListings; ++$i)
{
if ($i%5 == 0)
{
echo "in";
?>
<script> </script>
<?php
}
echo $listings[$i-1] . "<hr/>";
}
Here we are looping from 1 and there for $i <= $numberOfListings
and while listing we will use $listings[$i-1]
DEMO CODE AT http://codepad.viper-7.com/lrTOgP

Looping through specific array elements

I have a table and each row contains, among other things, 5 columns which may or may not contain an image file name. Let's say I've retrieved that row and put it into an assoc array. I want to loop through and echo those image file names (cols may or may not all be populated) into html tags, but only if that column has an image file name in it. Is there a better way to do it than this?
for ($i = 1; $i < 6; $i++){
if($item_array['image_' . {$i}]{
echo "<li><img src=\"images/work-items/$item_array['image_' . {$i} . '.jpg'\"/></li>"
}
Your syntax was all over the place:
for ($i = 1; $i < 6; $i++){
if(isset($item_array['image_' . $i])){
echo '<li><img src="images/work-items/'. $item_array['image_' . $i] . '.jpg"/></li>';
}
}

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)

Categories