Submit Your Article Forum Rules

Page 2 of 2 FirstFirst 12
Results 11 to 17 of 17

Thread: PHP loops?

  1. #11
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,793
    Found this by searching, examples of program loops, where the top result, though probably very old, is exactly what I wanted: Loop Examples.

    Notice right off the top the two main categories: Count controlled, and Event controlled. The language is not PHP, but a close look will reveal the salient information on how each type of loop within these categories works, and how it is controlled.

    In old BASIC speak, the simplest loop was, 10 GOTO 10. This one is the best example of an uncontrolled loop. A common use of this line was a listening post. Event listeners would trap events on the screen, the keyboard or the mouse and execute their toolbox code, but in the meantime, the program would just hang out at line 10, to which it would return after every event is handled.

    More elaborate examples can be drummed up, like a non-terminating slide show, or a repeating sequence of sampled music. Uncontrolled loops are also called 'infinite' in that they have no predefined end. They stop when the program stops. We definitely don't want any of these in a our PHP scripts or the page will never load, and the hosting provider will get mighty upset if it crashes their server.

    This is where controlled loops come in. We set strict limits, sometimes referred to as lower and upper bounds, when counting, or structure our data so that an end of file event occurs (such as above in the FOREACH() that PHP provides us) and forces an exit from the loop. We can also set exit conditions within a loop, which lets us minimize the clock ticks consumed by the server while executing it. We do that above, as well. Remember Z and F?

    Just so we're clear, there is no one loop that is best for all purposes. With time and practice and experimentation/invention you will set upon a choice of loop method best suited to the task at hand and the type of data being crunched.

    A simple counting loop (without employing actual loop functions within the given language) is, again in BASIC speak,
    10 A=0
    20 B=100
    30 A=A+1
    40 IF B-A=0 THEN END
    50 GOTO 10

    Here is a simple PHP counting loop
    $a = 0;
    $b = 100;
    do { $a++; } while ( $a < $b );
    echo $a . ", " . $b;

    One loop function built into most languages that keep all the controls in one place is the FOR() loop. In BASIC, this used to be a FOR TO STEP NEXT loop but languages evolved that led to C which led to PHP, which give us a more elegant, FOR(). Here is one that loops through what we have above:

    for ( $i = 0, $n = 100; $i < $n; $i++) { // do something }

    We can already see a difference in these two loops. In the former, the increment was the action within the loop, whereas in the latter, the increment is handled by the control expressions defined by the for() arguments, leaving the 'workspace' completely free of control variables, save a possible event trap that causes an exit. The code within the workspace will execute once for every increment of the control variable, just as above and will terminate when it reaches the upper bound.

    When working with one dimension arrays in PHP, the for() loop works great. It cannot equal the power of the foreach() loop when it comes to more sophisticated array structures (keyed indexes and arrays within array cells), though. While examining this language function, it will be good to immerse oneself in ASSOCIATIVE ARRAYS. They can be very confusing at first, and a clear understanding is necessary in order to properly understand and implement these loops with success. If you are familiar with JavaScript basic objects--Property : Value, then you will catch on quickly to, $key => $value.

    It gets hairy when $value is an array, also. But as a single dimension, this one can be parsed using for() or foreach() again, either one nested in the main foreach(). But now I'm getting ahead of things. You will not find the code in our example above very difficult to grasp once you envision the workings of the two main loops. The only other abstracts in the code are the REGEX used in the PREG_REPACE() function, and the construction of our letter array with PREG_SPLIT(). Both of these functions require thorough reading, which you will benefit from immensely.

    The string functions are pretty self explanatory, but they deserve a good reading up on, too. They are an important part of the engine, after all. Just as a fuel filter removes unwanted particles from gasoline before it reaches the injection system, our filter removes unwanted characters and forces the remainder into uppercase. The substr() function grabs the first character of the string, regardless of length. Just studying the basic PHP functions in our example enough to understand it, will open up on dozens of ways to use just these functions in powerful ways. Just remember, your PHP is not a program, it is a script, and must terminate at some point or the page will never be returned to the client.

    As loops go, you'll notice that our example is an infinite loop. It keeps requesting the same page, which is both form control and handler rolled into one, just as yours is. Let me know how you're making out, and if you wish to continue this discussion about loops, bring it back here. Other PHP topics will need to be in a new thread, though, since this one is about PHP loops.
    Last edited by weegillis; 04-10-2012 at 12:28 AM. Reason: typo

  2. #12
    Member
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    64
    Awesome work weegillis, I'm reading through things and the explanations are helpful but I have to admit that it's the examples you're giving which I like the most. I do have to admit that I am little lost from time to time with this information, but if you want to continue this, you can by all means keep posting in this thread or if you want to add me on Skype/msn I'd love to keep learning from you.

    As for the code I have running on the website, well I got it running before you posted your original reply, with a terribly heavy piece of code which is a repetition of the original if statement. No loop involved so the code it self is about 600 lines long.... like I said terrible but it works. I can see that your code works, but will not use it because it is your code in the end, and you have full rights to that. I honestly think I need to read up on arrays and loops across a few resources and perform a few examples so I can gain a good foot in the knowledge that is required.. effectively the reason I'm trying to learn this information is because I'm trying to create a bigger project, but I don't as of yet have the skillset to complete the project and require some learning to be done.

    Like you did say though, and I completely agree with you, if I understand correctly. You start from point A, and then with what you have developer or are developing, you should continue to progress as there is always another way to tackle the coding issue at hand, and by taking a new point of view you're able to discover more efficient ways to progress and innovate.

    PM me if you want to discuss some further subjects on Skype or MSN, I could use a few coders/hobbyiest coders in my contacts as it will allow for me to have further discussions and bounce ideas off. Also how long have you been learning php for?
    http://www.dynamicexposure.com - Photography Tutorials, Help and Forum.
    http://tibia.dynamicexposure.com - Tibia game information.
    http://phonetic-code.dynamicexposure.com - Phonetify - Phonetic Code for the words you enter

  3. #13
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,793

    Post

    In my opinion, you should use the code in post #7, with attribution in an HTML comment so it shows in the page source. If you want to include a URL in the comment, just point it tenfingers dot net/tools/atoalpha/. This is my working version. The one in post #7, is wpwversion.php at the same URL.

    Assuming you are going to be expanding the site to include other widgets (which this example could be known as) then keeping the PHP resources separate from HTML pages and templates so they can be re-used by all the documents on your site, not just the one page... would be good idea.

    The PHP above, would fall into the category, 'methods and modules' as there is no page generation involved, only data crunching or retrieval. The 'methods' (script procedures) include the functions along with the procedure starting with $var=. The 'modules' (what I call them) are the predefined array, $STACK, and, $NPD, defined as the string constant, "No POST data". Both of these are known as 'statements' in PHP. Since they have no closure (they are not contained within a function) their scope is global, meaning any function or method can call upon them. In our example, we can see that the main method is also without closure, so it too executes within the same scope as our global CONSTANTS and the statements that defined them. Anyway, this is getting away from things...

    index.php
    PHP Code:
    <?php require_once "library.inc"?>
    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Multiword Phrase NATO Phonetic Alphabet converter</title>
    <meta name="description" content="A PHP method to convert alphabet letters to their NATO phonetic callout">
    <style>textarea{width:400px;height:300px}</style></head><body>
    <form method="post" action="index.php">
     <input type="text" name="text" autofocus="autofocus" size="50">
     <input type="submit" value="Send"><br>
     <textarea disabled="disabled"><?php echo "Sent: $sentChar\nResult: $charResult\n"?></textarea>
     <textarea disabled="disabled"><?php echo "Sent: $sent\n&gt;&gt; $charResults\n"?></textarea>
    </form></body></html>
    library.inc
    PHP Code:
    <?php /* Multiword Phrase NATO Phonetic Converter by RC Pierce 2012-04-08 */
    $STACK=array('A'=>'Alpha','B'=>'Bravo','C'=>'Charlie','D'=>'Delta','E'=>'Echo','F'=>'Foxtrot','G'=>'Golf','H'=>'Hotel','I'=>'India','J'=>'Juliet','K'=>'Kilo','L'=>'Lima','M'=>'Mike','N'=>'November','O'=>'October','P'=>'Papa','Q'=>'Quebec','R'=>'Romeo','S'=>'Sierra','T'=>'Tango','U'=>'Uniform','V'=>'Victor','W'=>'Whiskey','X'=>'X-ray','Y'=>'Yankee','Z'=>'Zulu');
     
    $NPD "No POST data"
     function 
    postFilter($post) {
      
    $post preg_replace("/^[ ]+|[^a-z ]|^[ ]+$/i"""$post);
      if (!
    $post) return NULL;
      return 
    strtoupper($post);
     }; 
     function 
    postSplit($post) {
      
    $postChars = array();
      
    $postChars preg_split('//'$post, -1PREG_SPLIT_NO_EMPTY);
      return 
    $postChars;
     }; 
     function  
    alphaToPhonetic($post) {
      global 
    $STACK;
      foreach (
    $STACK as $alpha => $phonetic) { if ($post == $alpha) return $phonetic; };
     }; 
     function 
    wordToPhonetic($posts) {
      
    $result "";
      foreach (
    $posts as $index => $letter) { $result .= "\n" alphaToPhonetic($letter); };
      return 
    $result;
     };
     
    $var = ($_POST['text']) ? $_POST['text'] : NULL;
     if (
    $var) {
      
    $sent postFilter($var);
      if (
    $sent) {
       
    $sentChar substr($sent01);
       if (
    $sentChar) { $charResult =  alphaToPhonetic($sentChar); } else { $charResult $NPD; };
       if (
    strlen($sent) > 1) { $charResults wordToPhonetic(postSplit($sent)); } else { $charResults $charResult; };
      } else { 
    $sent $sentChar $NPD; };
     } else { 
    $sent $sentChar $NPD; };
     
    ?>
    Be sure to remember that the main method is without closure, and will execute every time this resource is called. To control 'when' it runs requires giving it closure within a function, or only including the resource when it is needed. For now, we are fine, but if you begin adding modules to this library, things might have to change.

    Why .inc? Again, arbitrary. I use .inc to signify m&m's. They are includes, so .inc works fine for me. The truth is it doesn't matter what you use for an extension on a PHP include file, as long as it's not an already defined extension or MIME type that the server has built in methods for handling. Unless configured, .htm, .html, among others, will not be parsed for PHP by the server.

    Notice the 'require_once' statement, above? This is how we attach the PHP to the HTML document. Now you may wish to keep your library out of the way, where it's safe. You can do this by creating a folder called 'includes' (again, arbitrary) and store the file in there. Your statement would then read, 'require_once "includes/library.inc";'

    I won't get into now, but you should know there are some real gotchas when traversing directories in PHP. Everything is happening in real time on the server, and if includes contain references to other resources, the location of the include file is focal to how the path is constructed pointing to those resources. Read up on getcwd() and other topics relating to Current Working Directory. Our example will work if you store it away in a folder, so not to worry. This would be the recommended approach.

    Last thing of note to this post... The markup is HTML5. As you can see, it is still HTML, just slimmer, and a lot more semantic. In our example there is nothing really that sets it apart from a normal HTML page, so I'll list the few things that are different: No type attribute on STYLE or SCRIPT; No long doctype; no Content-type or Language. I use HTML 4 markup, not XHTML, but both are valid, so pick one and stick with it or your pages will look in disarray.
    Last edited by weegillis; 04-17-2012 at 07:02 PM. Reason: completed sentence in par-2.

  4. #14
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,793
    Note: PHP is compatible with all versions of HTML. You can import the library into your existing page, no real changes required. Our example populates a TEXTAREA, but needn't be confined to that form of display. Just set the echo statements where they belong in your page. Give the output some style with CSS and you're done like dinner. Cheap and dirty! Just like that.

    Which is why I love PHP, even the elementary level that I'm at. Same goes for CSS. Every piece of code I have ever written was a solution to something--ultimately taking the leg work out of, or adding horsepower to repetitive tasks, aka., TAGGING and LOOKUPS. We have a web server that will do all the heavy lifting for us if we just give it a working set of instructions.

    We feed in data and PHP outputs it how we like, tagged up and ready to go. New data? No problem. The page handles whatever is thrown at it. Want to add an ALPHA BETA list, or one with xylophone instead of x-ray, just add a set of buttons or a SELECT control to the page. The action value could be a hash (if AJAX request) or a query string (page request) with the name of the alternate data set. Park the array data in a database (CSV, even) and load any number of different data sets into the one declared array. At the click of a button. And no core procedures ever need to be changed. We just add methods and modules to our library.

    You do realize that I am not a programmer, so you will of course take everything with a grain of salt. I am sharing amateur experience. Different from expert knowledge, but no less useful. One in our position will do best when we never allow ourselves to be so impressed that we don't question. This is where the learning is. Peer into a thing and make sure that it does what YOU want it to, and understand HOW it is doing it so you can CONTROL it.

    Without control, a script is an easy thing to exploit, and so becomes a security risk. We both have a lot to learn about security, and if I'm saying that to you now, after four years of hobby time spent on PHP solutions, then you know YOU don't know enough, because I presumably know more than you and I don't know very much at all.

    What I know is that valid input yields valid output (just saying) so making sure that all input is filtered and no wrenches get drawn in, is the first step in making sure that exploit code never gets through. All I know is it is first up to me to check for all errant data (form variables) coming from all form controls, especially TEXT.

    Our procedure above is fairly secure because it filters, then funnels the results through an inducer. The actual data never gets through, only the induced (stored) data. The postSplit() function pretty much destroys the original data, only to force its output through the inducer. But, hey! I could still be very disillusioned. Like I said. We both have a lot to learn about security.

    See what you can come up with by way of storing the data on disk, and retrieving it by data set into a page request. Most of the clues are already there, or discussed partially in my last post and this one.

  5. #15
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,793

    Post Tagging and Lookups

    I can't think of a more perfect example of raw lookup and tagging in one method. This is a page that can be dropped into any folder containing images (careful not to overwrite the index.php page, if there is one, otherwise use a different name) and the page displays all images tagged with width, height, alt and title attributes, scaled to fit the current viewport, along with links to view the full size image.

    There are two loops, one to query the folder, and one to generate the image links. We first store the results of the folder query in an array, then we parse through the array, full knowing that only images are listed, and create our HTML from the data in each record.

    Very powerful, and all it takes is dropping the index.php into a folder and there you have it.

    Your next assignment will be to make this a portable file, so individual pages can call upon it, and you only have one copy of it in the includes folder.

    Give it a whirl...
    PHP Code:
    <?php
     $img_handle 
    = array();
     if (
    $handle opendir('.') ) {
      while (
    false !== ($file readdir($handle) )) { 
       if (
    stristr($file'.jpg') || stristr($file'.png') || stristr($file'.gif')) {
        
    $img_handle[] = $file;
       };
      };
      
    closedir($handle);
     };
     
    sort($img_handle);
     
    $str " <table>\n";
     
    $count 1;
     foreach (
    $img_handle as $key => $v) {
      
    $istristr($v".");
      
    $j $i 4;
      
    $k substr($v0$j);
      
    $f filesize($v);
      
    $m date ("F d Y"filemtime($v));
      list(
    $w,$h) = getimagesize($v);
      if (
    $w>0) {
       
    $xw = (512 $w 1) ? 512 $w;
       
    $yh = ($xw==$w) ? $h : (512 $w) * $h;
      };
      
    $img "<img src=\"" $v;
      
    $img .= "\" width=\"" $xw "\" height=\"" $yh;
      
    $img .= "\" alt=\"" $k "\" title=\"" $m " : " $w "x" $h " : " . ((int)($f/1024) + 1) . "KB\">\n";
      
    $hrf "<a href=\"$v\" title=\"View $k in this window\">$v</a>";
      
    /* in lightbox
      $hrf = "<a href=\"$v\" title=\"Open $k in Lightbox\" rel=\"lightbox1\">$v</a>";
      */
      
    $str .= "  <tr><td>$count</td><td>$img</td><td>$hrf</td><td>$m</td></tr>\n";
      
    $count $count 1;
     };
     
    $str .= " </table>\n";
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <tile>image inspector</title>
    <meta name="robots" content="noindex,nofollow">
    <style>
    table#dir{width:100%;border:none;}
    table#dir td{width:25%;text-align:left;border:none;}
    table#dir td:nth-child(1){width:5%;}
    table#dir td:nth-child(2){width:50%;}
    table#dir td:nth-child(3){width:10%;}
    table#dir td:nth-child(4){width:35%;}
    </style>
    </head>
    <body>
    <div>
     <h1 style="font-size:smaller;"><?php echo getcwd(); ?></h1>
    <?php echo $str?>
    </div>
    </body>
    </html>

  6. #16
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,793
    We can use str_replace() to shorten the current directory printout to just site path and folder:
    PHP Code:
     <h1><?php echo str_replace('/this/that/public_html/','',getcwd()); ?></h1>
    Of course the this and that, and maybe even public_html are just placeholders for what you're seeing from your server. You get the idea. This is another string function to acquaint yourself with.

    In time you might begin to notice performance issues if your code gets CPU intensive. There are a gazillion ways to do things, but many clock up a lot of ticks. Optimizing your PHP to the task at hand is the way to keep these clock ticks down. The str_replace() function is one example of conserving energy. Read up some more on this, for sure.

  7. #17
    Administrator weegillis's Avatar
    Join Date
    Oct 2003
    Posts
    5,793
    Oh, yeah, the assignment thing was a gag, but if you wanted a hint..., break up the PHP from the HTML and require the PHP include. After that, style the heck out of your HTML output and you have a page, anywhere.

    <edit>
    Remember we spoke about 'portable'? The above T&L can be dropped into any layout, not just directly as a stand alone page. The salient parts can be inserted into any predefined page. Then again, portable layouts and php loops are a bit far aflung. Just worth noting.
    </edit>
    Last edited by weegillis; 04-13-2012 at 06:14 AM. Reason: lots of edits

Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •