PHP - Nested Loops
Hi guys and Marry Christmas to all of you who are celebrating! I'm traying to learn PHP on my own and I am stuck in traying to understand this concept of nested loops and using break/continue in them. So, can someone please explain to me how this code below is working and why I'm getting result that I don't expect. Code is: for($i = 0; $i < 6; $i++) { for($d = 0; $d < 4; $d++) { if($d == $i) { continue 2; } echo $d."d <br>"; echo $i."i <br>"; } } When I was writing this code I was expecting that result, because of continue 2, will be 4i and 5i. But instead of that I got this 0d,1i,0d,2i,1d,2i,0d,3i,1d,3i,2d,3i,0d,4i,1d,4i,2d,4i,3d,4i,0d,5i,1d,5i,2d,5i,3d,5i. I really want to how I got this result, I spent whole day traying to explain this to myself and failed miserably.
Similar Tutorials<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Second Testing</title> <link href="styler.css" rel="stylesheet" type="text/css" /> </head> <body> <?php error_reporting(0); $num_rows = 16; $number1 = 4; $inn = array(7,10,13,16); $outt = array(14,16,21,23); $numm = array(3,5,7,9); $r_time_in = min($inn); for($i = 0; $i <= $num_rows; $i++) { $new_r_timer_in[$i] = $r_time_in; $new_r_timer_out[$i] = $new_r_timer_in[$i] + 1; $r_time_in += 1; } // for($y = 0; $y <= $number1; $i++) // { // for($i = 0; $i <= ($num_rows - 1); $i++) // { // if(($inn[$y] <= $new_r_timer_in[$i]) || ($outt[$y] <= $new_r_timer_out[$i])) // { // $numb[$i] = $numm[$i] + $numm[$i - 1]; // } // else // { // $numb[$i] = $numm[$i - 1]; // } // } // } for($i = 0; $i <= ($num_rows - 1); $i++) { echo '<table width="526" border="0"><tr> <td width="169"> <input type="text" name="$r_in[]" value="'.$new_r_timer_in[$i].'" style="width:169px" readonly="readonly" class="text_non_color"/></td> <td width="169"> <input type="text" name="$r_out[]" value="'.$new_r_timer_out[$i].'" style="width:169px" readonly="readonly" class="text_non_color"/></td> <td width="169"> <input type="text" name="$r_num[]" value="'.$numb[$i].'" style="width:169px" readonly="readonly" class="text_non_color"/></td>'; } print("</tr>"); ?> </body> </html> the code above works very well in its current state. three columns are produced but only two have data, the third column is empty. when executed, the code is supposed to check whether a range(7 - is between the first element of array $inn and the first element of array $outt and then add the corresponding number in array $numm to the number in that(7 - range the commented out code is supposed to implement this idea but its not.........help. I'm trying to output this: Status Player Player Player Status Player Player Player Status Player Player I tried this, but it didn't work: Code: [Select] while($players = mysql_fetch_assoc($results)) { foreach ($players as $player=>$status){ echo '<div>' . $player['status'] . '</div>'; foreach ($status as $key) { echo $key['playerFirst'] . ' ' . $key['playerLast'] . ', '. $key['year'] . '<br>'; } } } I guess I'm trying to find a more efficient way of doing this rather than if/elseif for each one. Right now, there are only four groupings, but in the future there could be as many 406. i have been given this task in in uni. i was wondering it some one would be so kind to help me with it. all i have so far is this <?php for($x=1; $x<=3; $x=$x+1) { print "$x <br>"; } if ($x== "A") { } ?> the task is below Generate a number between 1 & 3 If 1 then assign A, If 2 then assign B, If 3 then assign C Add to a wordstring (using string concatenation with .) We need 3 letters generated to give a 3 letter word For loop (3) Generate a number between 1 & 3 If 1 then assign A, If 2 then assign B, If 3 then assign C Add to a wordstring (string concatenation with .) End loop Print 3 letter word Hi All, and thanks for your help on my last problem now solved. What i am doing is building a job site and it needs info put in from job seekers regarding their qualifications. Some will have 2 some may have 10 and so on. I need to set up a system that I can put say 10 text boxes in a form that can then go in a MySQL. I only want the filled out boxes to go into the database and not the ones left blank. I have no idea as to where to start with but I think I need to loop through until it comes to the last filled out box but not enter the blank text boxes. i have no idea where to start on this one so if any one has thoughts on this it would be great. Thank you all for your help in the past. Did PHP a few years ago and for the life of me i can't work out why this doesn't work: Code: [Select] for ( $counter2=1; $counter2 < 1000; $counter2++) { for ( $counter1=1; $counter1 < 1000; $counter1++) { echo "Fixed bug"; } } and yet this does Code: [Select] for ( $counter2=1; $counter2 < 100; $counter2++) { for ( $counter1=1; $counter1 < 100; $counter1++) { echo "Fixed bug"; } } I tested it because I have a rather large amount of data to retrieve from an XML file and i kept receiving errors I do not have the option that I know of to do a LIMIT 10 in my odbc query. How can I get it to count the number of while loops and stop at 10? Code: [Select] while (odbc_fetch_row($rs)) { } Hi guys
I just wanted to make a short post and talk about an issue im having and maybe get some advice. I know that loops aren't that hard to grasp and I shouldn't be having this much trouble understanding them but im just not getting it. I dont really know how to explain it but loops (like looping through mysql in an update statement) is foren to me and i was wondering if anyone had any advice for maybe learning them or maybe something im just over looking or maybe some good tutorials. I really want to get them down and start using them in scripts i right but im getting so frustrated because i constantly hear how easy they are and im just not getting it. if i wasn't clear please let me know and ill try to explain more clearly thanks guys JL i am having issues with my class work. this needs to start at the $startNum and end with the $endNum and display results in the increments submitted by the html. I can not get it to print out correctly it is supposed to say: The square of $startNum is $square //until it hits the end number and is going up by the correct increments, It wont go up by any increments and only shows a list if i leave out the increment-----any suggestions??? please i have to keep it very simple since i am just learning-ty html </head> <body> <h1>Squares</h1> <p> <form action = "squares2Boles.php" method = "post" > <p>Start with: <input type = "text" size = "5" name = "startNum" /> </p><p>End with: <input type = "text" size = "5" name = "endNum" /> </p><p>Increment by: <input type = "text" size = "5" name = "increment" /> </p><p><input type = "submit" value = "Display the Squares" /></p> </form> </body> </html> my php: <html> <head> <title>Squares</title> <link rel ="stylesheet" type="text/css" href="sample.css" /> </head> <body> <?php $startNum = $_POST['startNum']; $endNum = $_POST['endNum']; $increment = $_POST['increment']; $square = $_POST['square']; print ("<h1>SQUARES</h1><hr />"); for ($startNum = $startNum; $startNum <= $endNum; $startNum = $startNum + $increment) { $square = $startNum * $startNum; print ("The square of $startNum is $square<br />"); } print ("<hr />"); ?> </body> </html> i am a student and trying to figure out why this is not working for me i am trying to pull from my .txt file and add the lines. $numOrders should be 20 and $numCopies should be 52. it keeps telling me --Warning: feof() expects parameter 1 to be resource, string given on line 25. i really am having big trouble trying to understand how to use the while loop for this. any help would be great. here is my html code <html> <head> <title>Software1</title> <link rel ="stylesheet" type="text/css" href="sample.css" /> </head> <body> <h1>SOFTWARE ORDERS: REPORT</h1> <form action = "software1Boles.php" method = "post" > <p><input type = "submit" value = "Display the Report" /></p> </form> </body> </html> my php code <?php $totalCopies = $_POST['totalCopies']; $totalOrders = $_POST['totalOrders']; $nextOrder = $_POST['nextOrder']; $totalCopies = 0; $totalOrders = 0; $orderFile = fopen("ordersBoles.txt", "r"); $nextOrder = fgets ($orderFile); while (!feof($nextOrder)) { list($totalCopies, $totalOrders) = explode (":", $nextOrder); if ($totalCopies >=1 and $totalCopies >=1) { $totalCopies = $totalCopies + $nextOrder; $totalOrder = $totalOrder + $nextOrder; } $nextOrder = fgets($orderFile);} fclose($orderFile); print ("<h1>SOFTWARE ORDERS: REPORT</h1>"); print ("<p>TOTAL COPIES ORDERED: $totalCopies</p>"); print ("<p>TOTAL ORDERS: $totalOrders</p>"); ?> </body> </html> and my .txt file 1 Linux:1 2 Macintosh:1 3 Windows:1 4 Macintosh:1 5 Macintosh:2 6 Linux:5 7 Macintosh:10 8 Windows:10 9 Macintosh:1 10 Windows:1 11 Windows:1 12 Linux:1 13 Macintosh:5 14 Linux:4 15 Windows:1 16 Macintosh:1 17 Windows:1 18 Linux:2 19 Macintosh:2 20 Windows:1 21 anything you can give me would help alot, thanks Hello everyone, I've already posted a question trying to resolve my problem, but I've changed my code so much, I figured it may be best just to post a new thread with a better explanation of what I'm trying to do. Anyway, here's what I've got: I have a database with 2 tables: products and reservations. I have 3 products for now, that can be reserved for any date. I'm trying to create a page that will display all of the available products for a specific date. The user selects the date they want to check, and then the code should check their selected date and compare it with the database to display everything that is available on that date. The database looks like this: Products Table: prodid prodname 01 item 1 02 item 2 03 item 3 Reservations Table: prodid resdate 01 02/22/2012 01 02/23/2012 03 02/22/2012 Here is the code that I have now: Code: [Select] <?php $resultres = mysql_query("SELECT `prodid` FROM reservations WHERE `resdate` = '$resdate'") or die (mysql_error()); while ($rowres = mysql_fetch_row($resultres)) { $resprodid = $rowres[0]; $resultavail = mysql_query("SELECT `prodid` FROM products WHERE `prodid` != '$resprodid'") or die (mysql_error()); while ($rowavail = mysql_fetch_row($resultavail)) { $prodid = $rowavail[0]; echo $prodid; echo $proname; } } ?> When I select 02/21/2012, I get no results, where I should get all three products as a result, because none of them are reserved on this date. When I select 02/22/2012, I get a result of these products, in this order: 02, 03, 01, 02. I should get a result of ONLY 02, because this is the only product that isn't reserved for this date. When I select 02/23/2012, I get a result of 02 and 03, which in this case would be the correct return, because 01 is the only one reserved for this date. Any idea what I'm doing wrong here and how to fix it? Any help is GREATLY appreciated! hey guys, in my script i displays status' the users have posted. However when the users status' got over like 20, i noticed it was affected load times greatly as lots of SQL is looping. Code: [Select] <?php $sql = sqlcount(mysql_query("SELECT * FROM statuses LEFT JOIN users ON statuses.userid = users.id ORDER BY statusid DESC")); while ($row = mysql_fetch_assoc($sql)) { $status_id = htmlspecialchars($row['statusid']); $status = htmlspecialchars($row['status']); $time_posted = htmlspecialchars($row['time_posted']); $status_userid = htmlspecialchars($row['userid']); $sql2 = sqlcount(mysql_query("SELECT username,avatar_url FROM users WHERE id=$status_userid LIMIT 1")); while ($row2=mysql_fetch_array($sql2)){ $usernamestatus = $row2['username']; $avatar_url = $row2['avatar_url']; if (empty($avatar_url)) { $avatar = "<img src='$directory_self/images/default_avatar.gif' height='50px' width='50px' />"; }else{ $avatar = "<img src='$directory_self/photos/$usernamestatus/$avatar_url' height='50px' width='50px' />"; } echo '<div id="content">'; echo "<br />"; echo $avatar; echo "<a href=\"profile.php?id=$status_userid\">". $usernamestatus ."</a>"; echo "<br />"; $status = str_replace(array_keys($bbcode), array_values($bbcode), $status); echo $status; if($userid == $status_userid){ echo " <span class=x><a href=delete_status.php?id=$status_id>x</a></span>"; } echo "<br />"; echo format_date($time_posted); echo "<br />"; echo "<br />"; ?> <div id="like<?php echo"$status_id"; ?>"><a href="#" style="text-decoration: none" class="like" id="<?php echo"$status_id"; ?>"><span class="like_b"> <?php echo LANG_LIKE; ?> </span></a></div> <div id="unlike<?php echo"$status_id"; ?>" style="display:none"><span class="youlike_b"> <?php echo"$user"; echo LANG_LIKES_THIS; ?> </span><a href="#" class="unlike" id="<?php echo"$status_id"; ?>"><span class="unlike_b"> <?php echo LANG_UNLIKE; ?> </span></a></div> <?php echo "</div>"; } } ?> Is there a way to shorten this code and make it run faster, without as many queries? Cheers Hello, lately I have been having a problem with my simple PHP script. Out of the blue the following script doesnt seem to work properly, function sanitize_tags($content, $bad_tags = '') { foreach ($bad_tags as $tag) { $stripped_tags = str_replace($tag, '', $content); return $stripped_tags; } return $content; } $contents = "<html> <head> </head> <body>yutu<style>ghghl;kl;<script>hfjhk </body> </html>"; $bad_tag = array("<style>", "<script>"); $sanitize = sanitize_tags($contents, $bad_tag); echo $sanitize; Basically, when the function is invoked, only the first element in the array is used by the function. It seems like the second+ elements arent even iterated. Why is it only the first element is iterated? I have a feeling its going to be something extremely obvious. Thanks in advance. i am sorry for this reason English is bad I want to use two nested loops ( while ) Once the model code will loop as in the picture will come under the colors of the model and the model code 1.while only model result 2. while it is of colors and unit after exit loop next code Code: [Select] <table width="376" cellspacing="0" class="stats" width:100%> <tr> <td colspan="9" align="center"><?php echo $secim ?></td> </tr> <?php while(odbc_fetch_into($sql_result, &$row)) { $unit1 = floor($row[3]); $unit2 = floor($row[4]); $unit3 = floor($row[5]); $unit4 = floor($row[6]); $unit5 = floor($row[7]); ?> <tr> <td colspan="2" align="left" valign="top"><?php echo"$row[0]";?></td> <td>36</td> <td>38</td> <td>40</td> <td>42</td> <td>44</td> </tr> <tr> <td width="114" align="right" valign="top"><img src= <?php echo"images/Resize/$row[2]"?>></td> <?php //this table block 1.while only model 2. while it is of colors and unit after exit loop ?> <td width="25" valign="top"><?php echo"$row[1]";?></td> <td width="25"valign="top"><?php echo"$unit1";?></td> <td width="25"valign="top"><?php echo"$unit2";?></td> <td width="25"valign="top"><?php echo"$unit3";?></td> <td width="25"valign="top"><?php echo"$unit4";?></td> <td width="25"valign="top"><?php echo"$unit5";?></td> </tr> <?php } }?> <?php odbc_free_result($sql_result); odbc_close($connection); ?> </table> Hey everyone, Been a while since I posted. I hope everyone is doing well. I've built a couple of for() loops into my program and I'm getting some inconsistent results. The first loop I made was just a simple counter looking like this: Code: [Select] <select name="event_name"> <?php for($x = 1; $x <= 50; $x++){ if($x < 10){ echo "<option value=\"$x\">Event 0$x:"; echo "</option>"; } else{ echo "<option value=\"$x\">Event $x:"; echo "</option>"; } } ?> </select> This code works perfect. The 1st entry in my drop down list is event 1, then event 2 etc. now i have basically the same code on the another selection: Code: [Select] <select name="date" <?php for($x = 1; $x <= 24; $x++){ if($x < 10){ echo "<option value=\"$x\">0$x:00 EST"; echo "</option>"; } else{ echo "<option value=\"$x\">$x:00 EST"; echo "</option>"; } } ?> </select> however the generated code on this call starts with a result on 2 instead of 1 giving me 02:00 EST instead of 01:00 EST. I'm sure I could work around this by declaring some additional variables, but i'm just trying to figure out why i'm seeing different results between these two loops? any thoughts? thanks in advance for your help I'm trying to send an email that has a list created from a while loop to multiple people with an email list created from while loop. Can someone please help me figure this out? My brain is fried. Here's the code that I have: This is producing an error message that reads: Parse error: syntax error, unexpected '{' in /home/content/29/6879529/html/calhoun/admin/sendreport.php on line 22 Code: [Select] <?php include("conf.inc.php"); $result = mysql_query("SELECT `prefix`,`lname`,`email` FROM admin"); $row = mysql_fetch_row($result); $result2 = mysql_query("SELECT `to`,`from`,`subject`,`message`,`date` FROM allmsgs WHERE reported = 'n' ORDER BY `messid` ASC"); $row2 = mysql_fetch_row($result2); $cdate = date('m-d-Y'); while ($row = mysql_fetch_row($result)) { $prefix = $row[0]; $lname = $row[1]; $adminemail = $row[2]; $fullname = "$prefix $lname"; $sendto = "$adminemail"; $emailsubject = "Webstats Report For $cdate."; while ($row2 = mysql_fetch_row($result2){ // This is line 22. $to = $row2[0]; $from = $row[1]; $subject = $row[2]; $message = $row[3]; $datetime = $row[4]; $eachmessage = "<p> <hr width=\"400\"> To: $to<br> From: $from<br> On $datetime<br> <br> $subject<br>$nbsp;<br> $message </p>"; } $emailmessage = "<html> <body> $fullname, <p> Here is a list of the messages that have been exchanged in the last 24 hours.</p> $eachmessage </body> </html>"; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'From: Webstats <reports@webstats.com>' . "\r\n"; // Mail it mail($sendto, $emailsubject, $emailmessage, $headers); } ?> hi i have a db of tv shows, episodes and descriptions. they are in the db like: name | series | episode | description Friends | 1 | 1 | example Friends | 1 | 2 | example Scrubs | 1 | 1 | example I want to display it this way: Quote Friends Series 1 Episode 1 Series 1 Episode 2 Scrubs Series 1 Episode 1 cant seem to get it to fully work - it will display it for the first show but not do more than one thanks for any help Hi, I'm trying to create a script that imports a CSV file but gives the user 3 options: 1. If Exists Update 2. If Exists Keep Both 3. If Exists Ignore New The keep both is easy, I just insert everything without checks. However, the other 2 are a little bit tricky (in my mind anyway). I've been told I could create loops and that there isn't any easy way to do this with MySQL. I cannot use ON DUPLICATE KEY because the column that I'm checking cannot be unique (because I have the keep both option). Is it efficient in PHP to create a loop that checks each row to see if it exists? I'm a little hesitant because the files could be big and I'm not sure how efficient PHP is with CPU and memory resources. The App I'm making is designed to run in a business environment but it may run on servers that are handling more than one thing (not just web services). If anyone could give me a few pointers I'd be most grateful. Thanks. I don't want to have to use two foreach loops. Code: [Select] foreach($verify_partners as $verified) { echo $verified; echo $id; if ($verified == $id) { ?> <div> Remove </div> <?php } } It prints out as Array6Array6 Hello, can anybody help me with this question about variables within loops? Code: [Select] $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$filename'>" . $nt[$i] . "</a>" . "<br/>"; // LINE 7 $FileName = str_replace(' ','_',$nt[$i]) . ".php"; // LINE 8 $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> header.php Code: [Select] <p>HEADER UPDATED!</p> <p>the heading below should read (title goes here in capital letter)</p> <?php $title = $_GET['title']; $subtype = $_GET['subtype']; echo "<h1>$title</h1>"; echo "<h1>$subtype</h1>"; ?> When I echo $subtype I want subtype to be the file name of the page its displayed in. However thats not the case. Everypage I open is displaying the subtype of the previous page produced from my database. I assume that this is because $si = -1 is displayed before my loop. How can I get $filename in Line 7 to display the same as $filename in Line 8? Here's the code, I had used the query in the header, and now I'm using it to display the links in a table. What happens is that it only returns the first row and not the second third or fourth rows. When it does display the first row, it'll display it a lot of times. Here it is Code: [Select] <?php if($_GET['place']==addnetwork){ //display current networks echo "<table border=1>"; echo "<tr><td>Network Name</td><td>URL</td></tr>"; while ($query1 = mysql_fetch_assoc(mysql_query("select name,url from s_links"))) { $networkname = $query1['name']; $networkurl = $query1['url']; echo "<tr><td>$networkname</td><td>$networkurl</td></tr>"; } echo "</table>"; } ?> |