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.
?>
Related
What I'm looking for is looking for logic that allows you to print horizontal rulers between content, except for the last content block, which you do NOT want to close with a horizontal ruler.
I have this code to loop the number from 1 to 10 and I have this if inside to check if number is stored in database.
for($i=1;$i<=10;$i++){
if($i == $class->Check($i)){
echo $i;
echo "<hr>"; // if not the last!
}
}
I want to check here if it is the last data with the if condition not the loop, so if we got from if and the loop the numbers 2,3,4,7, I want to check with another if condition if it is the last number and print something.
Notice -> the for loop numbers isn't the same it's a variable this is just an example.
What is the code for (I have this loop and when if condition is true it print something then a hr tag, but I don't want the lase print to print a hr tag so I want to check if it is the last print with if condition to stop it from printing the tag).
In your condition, you can save your output in an array, instead of displaying it immediatly, and then, you can use it later, by checking if you are at the last value :
$MyOutput = [];
for($i=1;$i<=10;$i++) {
if($i == $class->Check($i)){
$MyOutput[] = $i;
}
}
for($i = 0, $len = count($MyOutput); $i < $len; $i++)
{
echo $MyOutput[$i];
if ($i == $len - 1) // are we at the last element ?
{
// your special message for the last element
}
}
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++)
Newb question: I'm using a foreach loop to get items from an array.
I need to start looping at an offset number- (I'm using a $i variable to do this, no problem).
But when my foreach reaches the end of the array I want it to start going through the array again until it reaches the offset number.
I need to do this so I can have a user open any image in an artist's portfolio and have this image used as the first image presented in a grid of thumbnail icons , with all the other images subsequently populating the rest of the grid.
Any ideas?
Please bear in mind I'm new to PHP! :)
See below for an example of my current code...
$i=0;
$limit=50;// install this in the if conditional with the offset in it (below) to limit the number of thumbnails added to the page.
$offset=$any_arbitrary_link_dependant_integer;
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};// end of add thumbnails loop.
$i = 0;
$limit = 50;
$offset = $any_arbitrary_link_dependant_integer;
$count = count($portfolio_image_array);
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit && $i < ($count - $offset)) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};
Only thing I added was a $count variable.
Edit: If your array starts at 0 I would suggest you put the $i++; at the end of your foreach loop.
A simple method is to use two separate numeric for loops, the first going from offset to end, and the second going from beginning to offset.
<?php
// Create an example array - ignore this line
$example = array(1,2,3,4,5,6);
$offset = 3;
// Standard loop stuff
$count = count($example);
for($i = $offset; $i < $count; $i++)
{
echo $example[$i]."<br />";
}
for($i = 0; $i < $offset; $i++)
{
echo $example[$i]."<br />";
}
?>
This is also almost certainly cheaper than doing multiple checks on every single element in the array, and it expresses exactly what you are trying to do to other programmers who look at this code - including yourself in 2 weeks time.
Edit: depending on the nature of the array, in order to use numeric keys you may first need to do $example = array_values($portfolio_image_array);.
Using Answer Question to force StackOverflow to let me post a decent length of text!
OK #Mark Walet et al, not sure how to post correctly on this forum yet but here goes. I got the issue sorted as follows:
$i=0;
$offset=$image_to_display_number;
$array_length = count($portfolio_image_array);
// FIRST HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from offset (chosen image) to end.
if ($i >= $offset && $i <= $array_length) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
$t_total++;// update thumbnail total count.
}
$i++;
}// end of foreach loop 1.
$looped=true;// Just FYI.
$i=0;// Reset.
// SECOND HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from beginning to offset.
if ($i < $offset) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
}
$i++;
}// end of foreach loop 2.
Thankyou so much for all the help!
:)
as #arkascha suggested use modulo operator
<?php
$example = array(1,2,3,4,5,6);
$count = count($example);
$offset = 3;
for($i = 0; $i < $count; $i++) {
$idx = ($offset + $i) % count
echo $example[$idx]."<br />";
}
?>
// begin table centered with a border
print ('<table align = "center" border = 1>');
$index = 0; // initialize index
for ($i=0; $i <= $rows; $i++) {
print("<tr>"); // start row
for ($k=0; $k <= $columns; $k++) {
$index++; // increment the index value
// make sure we don’t exceed array bounds!
if ($index <= $num_items) {
tableContents( $images[$index],
$names[$index],
$item_num[$index],
$item_description[$index],
$item_price[$index],
$index);
}
else {
print("<td></td>"); // make blank cell
} // end if $index…
} // end inner for
print("</tr>"); // end row
} // end outer for…
print ("</table>"); // end table
I am creating a basic php webpage that puts items in a table, however something is wrong in my for loop and I need a little help. The arrays aren't starting at 0 it seems, my $index variable is supposed to start at 0 and then increment but its spitting out the 2nd item at the beginning instead.
Any help would be appreciated! Thank you.
You have $index++ before you select your elements, that's why it starts at 1. Move it after the end of your if-else statement.
Also, per comment below be sure that your arrays don't get out of bounds. That is, if there are n elements in your array, the last element has the index of n-1. So, you probably want $index < $num_items, as well as $k < $columns and $i < $rows.
Ive managed to loop through a table and get the difference in days between 2 dates adjacent to each other in the table.
Multiple entries have the same date, i have it now that when that date changes, it displays an image however i want it to display the image as many times as the difference in date
$sql = mysql_query("SELECT * FROM Films_Info")
or die(mysql_error());
$last_value = null;
while ($row = mysql_fetch_assoc($sql)) {
if (!is_null($last_value)) {
$a = new DateTime($row['FilmRelease']);
echo "<p>".$row['FilmName']."</p>";
$interval = $a->diff(new DateTime($last_value));
//echo $interval->format('%d days');
$i = 0;
}
$howManydays = $interval->days;
for ( $i; $howManydays; $i++) {
echo "<img src=\"day.jpg\" />";
$howManydays = 0;
}
$last_value = $row['FilmRelease'];
}
for ( $i = 0; $i < $howManydays; $i++) The second is a conditional statement telling when the loop should stop.
The first section in the for loop where it says $i = 0 initialized the variable $i to 0 and then tests the condition $i < $howManydays.
Let's say $howManydays equals 1. That means 0 < 1, so the loop will perform.
At the end of the loop, the third section is called ($i++), so $i is incremented and now equals 1. The second section is called again to test conditions $i < $howManydays which is asking if 1<1 which it's not, so the loop will exit.
So if $howManydays is greater than 0, the loop should happen the integer amount that is in $howManydays.
You will want to remove $howManydays = 0; within the for loop, if you don't want it to only fire once.
The for loop
for ( $i = 0; $i < $howManydays; $i++){
// ...
}
is somewhat equivalent to the while loop:
$i = 0;
while ( $i < $howManydays ){
// ...
$i++;
}
http://php.net/manual/en/control-structures.for.php for more information
In your code above, you should also check if interval was set. You should probably just do an if rather than a while, if only need one interval.
you could just do a simple division on the interval and print out the image that many times
$last_value_u = $last_value->format('U');
$a_u = $a->format('U');
$interval = $a_u - $last_value_u;
$image_count = intval($interval/86400);
for($i=0;$i<$image_count;$i++)
echo "<p><img src=\"day.jpg\" /></p>";
Update
An alternative option would be to loop through the interval:
for($i=$last_value_u;$i<$a_u;)
{
if(intval(($a_u - $i)/86400) == X)
{
// run special code for specific day
}
else
{
// run code for every other day
}
$i+=86400;
}