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
}
}
Related
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.
When looping through an array how can I create a different css div style for the last element to be output in my array.
for($i=0;$i<=count($productid);$i++){if($productrank[$i]>0 ){
<? if (($productid[$i] % 2 ) && !( last element of array){ echo '<div class="centerBoxContentsFeatured centeredContent back vLine " style="width:50%;">';}
else { echo '<div class="centerBoxContentsFeatured centeredContent back " style="width:50%;">';} ?>
Just check if it is the last $productid
for(...)
{
if ($i === (count ($productid) - 1))
// Last one -> special CSS
}
}
Also, DO NOT use count() in a FOR loop if you don't really have to.
Just assign a value BEFORE and use it :
$count_temp = count ($productid);
for ($i = 0; $i < $count_temp; ++$i)
And use this $count_temp again if the IF statement to check if it's the last element
Answer to comment :
How would this same method get the first element?
if ($i === 0)
Or
// Special CSS for $i = 0
// Start loop at 1 instead of 0
for ($i = 1; $i < $count_temp; ++$i)
You can do this purely with CSS using :last-child. It is supported by all modern browsers.
div.centerBoxContentsFeatured:last-child {
/* special styles for last */
}
See it in action: http://jsfiddle.net/9y93j/1/
Like this:
if($productid[$i] == $productid[count($productid)-1]){
//last element code here
} elseif (($productid[$i] % 2 ){
//even row code here
} else {
//odd row code here
}
The following is a code block that's working fine as regards getting the data I want.
Don't laugh, it's probably inefficient, but I'm learning :)
What I want, is to use the $totalLength variable, to stop gathering data when the $totalLength is, say 1500 bytes/characters (ideally, ending on a full word, but I'm not looking for miracles!). Anyway, the code:
$paraLength = 0;
$totalLength = 0;
for ($k = 0; $k < $descriptionValue->length; $k++) { //define integer k as 0, get every description using ($k = 0; $k < $descriptionValue->length; $k++), increment the k loop (to get only 14 elements, use ($k <= 13))
$totalLength = $totalLength + $paraLength;
echo $totalLength." Total<br />";
$descNode = $descriptionValue->item($k)->nodeValue; //find each description element
$descNode = trim($descNode); //trim any whitespace around the element
$descPara = strip_tags($descNode); //remove any HTML tags from the elements
$paraLength = (strlen($descPara)); //find the length of each element
//if (preg_match('/^([0-9 ]+)$/', $descPara)) { //if element starts with numbers followed by a space, define it as a telephone number
// $number = $descPara;
// fwrite ($fh, "\t\t".'<div id="tel">'.$number."</div>\n"); //write a div with id tel, containing the number
//}
//else
if (preg_match('/[A-Z]{4,}/', $descPara)) { //if element starts with at least 4 uppercase characters, define it as a heading
$heading = $descPara;
$heading=ucfirst(strtolower($heading)); //convert the uppercase string to proper
fwrite ($fh, "\t\t".'<div id="heading"><h4>'.$heading."</h4></div>\n"); //write a div with id heading, containing the heading in h4 tags
}
else if (preg_match('/\d*\.\d{1,}[m x]/', $descPara)) { //if the element contains any number of digits followed by a dot, at least one further digit and the letters m x, define it as a heading based on it containing room measurements (this pattern matches at least two number after the dot \d*{2,}}
$room = $descPara;
fwrite ($fh, "\t\t".'<div id="roomheading"><h4>'.$room."</h4></div>\n"); //write a div with id roomheading, containing the heading in h4 tags
}
else if (preg_match('/^Disclaimer/i', $descPara)) { //if the element contains the word Disclaimer, define it as such
$disclaimer = $descPara;
fwrite ($fh, "\t\t".'<div id="disclaimer"><h4>'.$disclaimer."</h4></div>\n"); //write a div with id disclaimer, containing the heading in h4 tags
}
else if (strlen($paraLength<14 && $paraLength>3)) { //when all else fails, if the element is less than 14 but more than 3 characters, also define it as a heading
$other = $descPara;
fwrite ($fh, "\t\t".'<div id="other"><h4>'.$other."</h4></div>\n"); //write a div with id other and the heading in h4 tags
}
else {
fwrite ($fh, "\t\t\t<p>".$descPara."</p>\n"); //anything else is considered content, so write it out inside p tags
}
}
$totalLength counts nicely, but when I tried to put a while statement in there, it just hung. I tried putting the while statement before and after the for, but no joy. What am I doing wrong and how best to solve this one?
FYI $descriptionValue, is data parsed from HTML using DOM & xpath, the while I tried was while($totalLength <= 1500)
Maybe this is what You want:
if ($totalLength > 1500) {
break;
}
Just put a condition inside your for loop. It will jump outside the loop as soon as the condition evaluates to true.
// for () { ...
if ($totalLength > 1500) {
break;
}
// }
Basically, break ends execution of the current for, foreach, while, do-while or switch structure. You can find more about PHP's control structures in the manual.
You can also delete the for and add
$k = 0;
while ($totalLength <= 1500 || $k < $descriptionValue->length)
and inside the loop you increment the value ok $k
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.
?>