Nov 21, 2009

For ... Next Loops And Script Planning - My Fifth PHP Tutorial

free web hosting
Open Discussion > MODERATED AREA > Tutorials

For ... Next Loops And Script Planning - My Fifth PHP Tutorial

ghostrider
Be sure to read the other ones. They are located in the TUTORIALS section, and at the time of this writing all on the first page.

Intro To PHP
Tutorial 5 - For ... Next Loops and Planning Scripts
Released 4/15/07
By Chris Feilbach aka GhostRider

Contact Info:
E-mail: assembler7@gmail.com
AIM: emptybinder78
Yahoo: drunkonmarshmellows
Website: http://www.ghostrider.trap17.com

Before I start talking about what wonderful things loops are and all the cool stuff they can do, I want to address something first. I was asked about something to write in PHP. There isn't much you can really write yet, if your learning from my tutorial. You could always process some form data and practice writing conditional statements.

I have a couple main goals in releasing this tutorial. The first being to teach PHP, but I want to teach you more than that. I want you to be able to know what it is really like to program. Programming is a lot of the time taking smaller ideas, like conditional statements and loops and stuff, and putting them together to form a big picture. The things you are learning now will help you best to do that. I believe what makes programmers truly great is their ability to solve problems, and to be able to put together small bits of code that makes something truly useful out of it.

My goal is that after a couple more tutorials you'll know enough to hopefully start building your own scripts. So I'm going to talk about a little bit about how to plan for a script.
client
The first think I ask myself, or ask a PHP customer of mine, is "What do I/you need my script to do?". Don't over work yourself here. Always start out small until your ready to handle more.

Let's say, for whatever reason, you need a script that displays 5 random numbers between 0 and 60, and tells us whether the number is even or odd.

Think about it for right now. You need not think about it in terms of PHP, or even how a computer program would do it. Think about how you would do it. Take some time, and have an answer in your head before you move on.

My answer in my head was that I would determine what the 5 numbers are, and then look at the numbers. If they end in 0, 2, 4, 6, or 8, then they are even.

Now that you have a good idea in your head on how to do it, lets think of it from a programming aspect.

Think about it again. Don't just look down at what I am going to type.

Firstly, you will need 5 variables for your random numbers. Lets make a numberical array for that to make life easier. We also need to determine whether the number is even or odd. Divide it by two, and if it ends in .5 then it is odd. Otherwise it is even. We can use an if ... then statement for that.

Typing out code five times long is not only a waste of space, its boring even if you are using copy and paste! I am going to introduce to you the programming concept called for ... next loops. For ... next loops have a starting value, a condition which stops the loop, and also the option to either increase or decrease the starting value. $i is almost ALWAYS used for the starting value. Loops usually start out on zero, like arrays.

Like conditional statements, you will want to indent all of your loops. It makes things very easy to read and debug.

CODE
<?PHP
    for ($i=0;$i<=4;$i++) {
    print("Hello World!<br>");
    }
PHP?>


The above is a for ... next loop. Start with an indent and a for. $i=0; defines $i as the starting variable, and sets it value to zero. $i<=4 is the ending condition. As long as $i is less than or equal to 4 the loop will continute. $i++; means that $i is increased by one everytime to loop is repeated.

One of the biggest problems I had with learning for ... next loops was that the ending condition is true, and once it becomes FALSE the loop ends. Its backwards from other languages I have learned. However loops are important. Now, to our example. You may view it at http://www.ghostrider.trap17.com/tut/php5

The increment statemnt ($i++) can also be $i-- (subtract one), or something like $i + 1;, or even $i * 2. This statement is weird, it doesn't require a semicolon.

We need to get five random numbers. The function rand(min, max) will give us a random number between min and max. We can use a for ... next loop to populate (fill up) our array. We can then use another loop to figure out whether they are even or odd, and store that in another array. And we can use yet another loop to print the data.

Before we begin coding, I need to introduce some stuff about division in PHP (and many other languages). There are two types, floating point division, and integer division.

Floating point division, which is signified by a forward slash (/), returns a decimal. Integer division does not. Integer division is signified by a back slash (\).

CODE
<?PHP
$temp = 5 / 4;
print $temp; // Prints 1.2
$temp = 5 \ 4;
print $temp; // Prints 1
PHP?>


When using integer division you can use the percent sign (%) to return the remainder.

CODE
<?PHP
$problem = 5 \ 4;
print "5 over 4 equals $problem.<br>";
$remainder = 5 % 4;
print "The remaind of 5 over 4 is $remainder.";
PHP?>


CODE
<?PHP

// Use a numerical array to collect our data.  Our array is going to start on zero.

    for ($i=0;$i<=4;$i++) {
    // $i starts on zero, the loop runs until the loop is greater than four.
    // We could also have written is like this, ($i=0,$i<>5;$i++) {
    // That would run when $i is not equal to five.  It is identical to the loop above.  The <> symbol is the same as != , it means not equal to.
    $numbers[$i] = rand(0, 60);
    }
// We now have our values.  Let's create another array, $evenodd, that holds whether each number is even or odd.  For simplicity, we will put an "o" if it is odd, and an "e" if it is even, but I often use either 0 or 1, like other programmers.

    for ($i=0;$i<>5;$i++) {
    // Odd numbers, when divided by 2 have a remainder of 1.
    $temp = $numbers[$i] % 2;
        if ($temp == 0) {
        // The number is even.
        $evenodd[$i] = "e";
        } else {
        $evenodd[$i] = "o";
        }
    }
// Just for fun lets print the numbers out in reverse order than we generated them.
// Lets make the page nice, too.
print("<html><head><title>5 Random Number Project</title></head><body>");
    for ($i=4;$i<>-1;$i--) {
    print $i . "<br>";
    print $numbers[$i];
        if ($evenodd[$i] == "e") {
        print("  Even");
        } else {
        print("  Odd");
        }
    print "<br>";
    }
print("</body></html>");
PHP?>


And there we have it! An awesome random number generator. I'm not quite sure what I want to teach next, but I promise it will be interesting.

 

 

 


Comment/Reply (w/o sign-up)

alex7h3pr0gr4m3r
It's a nice tutorial. Why did you not put this with your other tutorials though?

As a php coder myself, I'd have to say for loops suck. I hate them. Sure they save you time, but they just make me angry. They're for people who are too lazy to use a while loop. A while loop can be used for everything, and a for loop is limited to just counting. Nothing against your tutorial though, just ranting on. I'm glad you posted this for those who didn't exactly know what a for loop was. It would have been nice to also have seen a for-each loop explained, (as much as i hate those too). Anyway that's beside the point. Keep up the good tuts!

tongue.gif

Comment/Reply (w/o sign-up)

slushpuppy
Very nice tutorial! How about combining foreach and while loops(If you haven't done before) into this tutorial?

Comment/Reply (w/o sign-up)



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : , loops, script, planning, php

  1. [phpbb] Member Last-visit Report Script
    for phpbb2 databases (0)
  2. Fruity Loops Tutorials-arpiggeator
    learn to use an arpiggeator giving stunning mellodys to bland chords (1)
    Software/Fruity loops. Tutorial covering / arpiggeator VST Used / Nexus (you can use nearly all
    other VST plugins as most if not all of them have a built in arpiggeator) Tutorial level /
    Begginer-Intermedeate/ Files /arp piano+chord.mp3/arp alone.mp3/no arp piano+chord.mp3/arp piano
    low.mp3/no arp piano alone.mp3/arp tutorial midi.mid/ you can obtaine the midi file here
    --------------------------------------- you can obtaine the mp3 files here
    --------------------------------------- Welcome to my tutorial on the effect called arpiggeator.
    the arpiggeator/arp i....
  3. Fruity Loops Tutorials-trance Style Songs
    How to create and use a profesional trance style bass mellody (13)
    Creating a bass mellody tutorial Software / fruity loops VST Plugins / Nexus,VANguard Song Style
    / Trance Tutorial Level / Beginner files needed to download bellow. ok to start I am going to
    teach you how to create what's sometimes referd to as a bass mellody. A bass mellody is used in
    most trance songs as its primary function is to fill out the song by this I mean make the song sound
    a bit fuller to add depth to it. a bass mellody is never made of more than a few note styles. see
    below In the above image you can see that I have use in all a total of t....
  4. Making A Song In Fruity Loops Part Three
    part three precusion (1)
    ok part three now which covers the precusions setup of the small song i built for this tutorial.
    the nesecery files can be downloaded here the image below is included in the precusions folder as
    it mught not be entierly visable within this post so shold you need it its there also the images
    purpose is to enable you to see what i am refering to within this tutorial lateron. now what i
    have done above is blackd out every pattern that has nothing to do with the precusion. so the
    patterns displayed in light grey are the only patterns i will be refering to. ok lets b....
  5. Making A Song In Fruity Loops Part 2
    part 2 the second melody (0)
    ok i am going to attach the midi file againe incase you didnt get it from the first part in this
    part i will demonstright how to create and insert the second mellody ok so you have your first
    mellody wich is ecetially the comein chord as i call it. now open the midi file you put in your left
    panel during the first tutorial and drag the mellody 2 © onto the pallet but click on pattern two
    in the right site playlist box. now like in the first tutorial replace with sytrus. for this type
    of mellody use something in the leads section of the plugin.for this you need to ....
  6. How To Create A Song In Fruity Loops Using Vanguard
    but you can use outhers (1)
    ok i began by trying to create individual tutorials for the creation of a song in general but as i
    make songs in fruity loops i thaught it better to teach you how to create a song inside fruity loops
    using anumber of efects and plugins. this is the bit of song we are going to learn how to create
    (note this song is copryrited to me so dont try claim it as yourown, i do give permision for you
    to remix it aslong as the title is displayd in this way in its entierty DJ StarSkream, solar
    flare(your name REMIX)) ok step one once you have downloaded the song snip abo....
  7. Background Image Swap Script
    Change a Background Image based on clock time (15)
    Background Image Changer Script To swap the background image from your CSS file according to the
    Server Clock Time. 1.) In your CSS file, add the following rule: CODE body {     background:
    url(time.png); } 2.) Create a "folder" named time.png. 3.) Into the folder, place three images
    named morning.png, day.png, night.png. 4.) Also, in the same folder, create an index.php file and
    copy/paste the following script. CODE $hour = date('H'); if ($hour     $image =
    "morning.png"; } elseif ($hour      $image = "day.png"; } else {      $image = "night.pn....
  8. Image Rotator Script (another One)
    easy to implement (0)
    In case you haven't noticed, I have a different Avatar display on the Forum each time the page
    is refreshed. /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif"
    /> For those of you who might want the script to do that, here is the one I am using: HTML
    $filesp = glob('*.png'); if(empty($filesp)){ echo 'no images found...die br >';
    die(); } else{ foreach ($filesp as $file) { $img_array = trim($file); } } shuffle($img_array);
    //select image at random header("C o n t e n t{dash}t y p e: image/png"); // replace th....
  9. How To: Ip Configuration Script (win Xp)
    If you travel a lot with your laptop, and need to switch between diff (0)
    How To: IP Configuration Script (win XP) If you travel a lot with your laptop, and need to switch
    between different IP's in different locations, this script is for you. There are many programs
    that handle this task very well, but they cost sometimes pretty big money. This tutorial will show
    you how to make your own IP Configuration Script for free. This script is for a static ip address
    configuration and is based on a little program called "NETSH.EXE" which is supplied with Windows.
    How it works. QUOTE Microsoft Windows XP - Using Netsh Netsh.exe is a....
  10. Using An Actionscript In Flash For Loops
    (0)
    QUOTE When you are dealing with a lot of data, you without a doubt will run into the need to use
    loops. Lets say you would want to attach a movieClip to the stage. If its just a few clips it
    won't form a problem, but what if you wanted to attach a lot more clips? It would be impossible
    to set them up piece by piece. It would take hours of coding the same code over and over again and
    that redundancy is something you could really do without, not even talking about the time you are
    loosing. This is where loops come into action. We have a few different ones to our d....
  11. Php Script To Make A Link List
    From the list of the Directory Files (6)
    Well, it has been a while since I have added anything to the Tutorial Sectiion, so here is another
    script for the members to enjoy. This one creates a list of links from the contents of the directory
    which it is run from. For instance, if you run it from the public_html folder, then all the files
    (not the Directores) are listed and linked so when you click on the link, that file is parsed and
    output to the browser. Here is the code: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    An XHTML 1.0 Strict Page to List the files in this directory ....
  12. Php Menu Bulding Script And Site Template
    available for download (0)
    A Php Menu-builder Tutorial This Sidebar Menu-builder code and the php scripts are adapted from
    a Tutorial on the Astahost.com Forum titled : CMS101 - Content Management System Design .
    Since the original tutorial's author (vujsa) did such a marvellous job of describing the system
    in the original Topic posting, I will not attempt to explain it here, rather, I invite you to have a
    look at his Topic and learn from it. The Basic tutorial provided coding for developing a table-based
    web-site template which used php includes and embedded data to create a &....
  13. Script To Build A List Of Links
    from filenames and h3 tags (2)
    Another Unordered List Script If you remember this Script , that tutorial was about creating
    an un-ordered list of links from a list of files contained in a Folder which was specifically named
    in the script. This current Tutorial goes several steps beyond that first Tutorial by being able to
    create a list from several folder names and, more importantly, the script reads the list of links
    from a 'flat file' rather than depending on the name of the folder to be hard coded in the
    script. It is only one small step to have the folder names found in a mysql ....
  14. Page Generation Time Script
    A script to tell how long it took to generate (17)
    this is a script used to tell you or visitors how fast your page was generated for the person who is
    viewing it... Ok it is verry simple!! all you have to do is put this script on every page... that
    you want it to be on CODE $starttime = explode(' ', microtime()); $starttime =
    $starttime + $starttime ; ?> and put it before everything on the page, for me i put it right
    underneith the DOCTYPE script which i think is a bloody waste of space to have it on there, but
    anyways.. i put it right below that and it works fine!! now where you want the time it....
  15. Verifying Email Addresses
    Using a simple PHP script (9)
    This simple script will allow you to run some basic checks to make sure that any email address
    entered is actually an email address. There is no guarantee offered that this will stop every single
    fake email address, but it'll provide some protection. Now, the code! First we need to get the
    email address to verify. Here, I get it using POST from an HTML form. CODE //Load email
    address from web form $email = $_POST ; Now, we move on to our first check. Does the text that
    has been entered look like it could be an email address? This check can be performed....
  16. Installing Ndstats!
    The greatest Stats script of all time. (4)
    An example of this script cna be found at http://www.own.tc/ (click enter) This is by far the
    BEST stats script and most sites use it! This is a PHP script and requires you to include files
    (Please... don't do iframes!) DOWNLOAD LINK: GO TO www.ZYMIC.com and go to Php scripts>stats
    scripts> and the current version of NDSTATS. Downlaod it and unzip it! Go to your WWW directory and
    create a folder called "ndstats". Then what you need to do is upload all of your files into that
    folder. You all should know how to do that. Then go to the top of the page(s) you wan....
  17. Random Quote Script
    (6)
    Here's a little random quote script that you can use to randomly choose from an array of quotes
    you provide. It's very easy to use on any page as it's an external script, you just call it
    from your page. I wouldn't use it for any more than about 50 quotes though, it would probably
    slow your site down too much. Here's the code: var ar = new Array(44) ar = "Do not meddle in
    the affairs of wizards, for they are subtle and quick to anger." ar = "Faithless is he that says
    farewell when the road darkens." ar = "I cordially dislike allegory in all its ....
  18. How To Use Trap17 Cgi Formmail
    a built-in script in every hosting (15)
    This tutorial is using TRAP17 hosting's built-in script called cgiemail. There are several
    hundreds of free scripts you can download and install it yourself but why not use what is already
    provided for you, if all you need is a simple submit and data collection? Let's begin. There
    are three things you need to remember: 1) you can rename the file however you'd like 2) two
    files (which I'll name them submitForm.html and template.txt ) must be in the same directory
    3) first two lines in template.txt must EXIST. Write your submitForm.html (where you ....
  19. [php] Simple Newsletter Script
    (17)
    This tutorial will give you the code needed and tell you how to implement it. First off you need to
    create a file called mailing.php this will be the file that processes the adding of emails to the
    list. CODE $email = $_POST ; $file = fopen("mailing.txt", "a"); fwrite($file, "\n" . $email);
    fclose($file); header("Location: mailing_thankyou.php"); ?> Next you need to create a file
    called mailing_thankyou.php , simple a page thanking them for signing up. Now create a file called
    mailing.txt with nothing in it, when uploaded to the server set it writable (c....
  20. Secure The Email Addresses On Your Website!
    Wonderful script and useful! And working (10)
    Just follow the instructions below: /* Secure Email Function by Juan Karlo Aquino de
    Guzman Website: http://www.karlo.ph.tc and http://www.abs-cbn.ph.tc E-mail:
    http://www.karlo.ph.tc/send.php Usage: showEmail("support@microsoft.com",0); OR
    showEmail("support@microsoft.com",1); Types: 0 = ordinary random 1 = more secure random To
    include to a script: include_once("email_secure.php"); */ And here is the code :
    CODE /*     Secure Email Function by Juan Karlo Aquino de Guzman     Website:
    http://www.karlo.ph.tc and http://....
  21. E-mail Mailer Script 0.1
    useful for website visitors (4)
    Are you pissed off when you are putting e-mail in your website, you always get spammers? Well,
    here's the solution. Just change the default variables to anything that you like, etc... follow
    the instructions on the script.. Here it is... hope you like it /smile.gif' border='0'
    style='vertical-align:middle' alt='smile.gif' /> CODE //E-mail Mailer Script 0.1 by Juan
    Karlo de Guzman //FOR TRAP17 ONLY... DEMO VERSION... DO NOT DISTRIBUTE header("Content-type:
    text/html; CHARSET=UTF-8"); $int_rand=mt_rand(1,20); if($int_rand>10) {
    $random_numbers=sha1(mt_ra....
  22. Simple Php Counter Script
    How to make a simple php counter script (2)
    In this tutorial i will explain how to make a simple script writen in PHP...that uses .txt file.
    CODE // script writen by tema $a = fopen ("count.txt", "r"); // 1. $bytes = 4;         $x =
    fread($a, $bytes); // 2. $y=$x + 1;                   // 3. $fp = fopen ("counter/count.txt", "w+");
     // 4. fwrite ($fp, "$y");     // 5. fclose ($fp);                // 6. echo "Posjeta:$y";          
         // 7. ?> 1. selecting a file which the script is going to use for counting visits. 2.
    reading from the script 3. adding 1 to the number in the .txt file. 4. opening....
  23. Email Script/form With Php
    how to make a simple email script using php (37)
    Today, I'm going to show you how to make an email script using PHP and HTML. Most people usually
    put Email me if they want an email link on their site, but there are several cons to this.
    First, it's very inconvenient for those people who use web-based mail such as Yahoo!, Hotmail,
    or Gmail because that darn Micro$oft Outlook program comes up if one accidently click the link.
    Second, you are very suseptible to spam bots because they scan your HTML source code for anything
    with the same pattern as an email address and add it to their database. If you are pre....
  24. Php Guessing Script
    Script game.. (4)
    Here's the guessing script, they guess a number and checks if they are right or wrong.. CODE
    if($action==yes){ //have the number that they are suppose to guess... $guess=14; //end
    if($t_guess==$guess){ print "Good job! Guess was right!"; }else{ print "Guess was wrong! Try
    again!"; } } ?> Thats it /smile.gif' border='0' style='vertical-align:middle'
    alt='smile.gif' /> ....
  25. Php Quiz Script
    Make quizzes for your site. (29)
    Hello all, A little bit back I decided to make a quiz scriptjust out of no where lol. However it
    doesnt do anything special but I am going to make an email mod for it so that it will email results
    to your email address. So here is the basis of it. INSTRUCTIONS: Open a new page in your text
    editor and paste in the following code. CODE $qid = "Quiz ID-00"; ?>
    Username: 1.) Question number one is? Answer1 Answer2 2.) Question number two is?
    Answer1 Answer2 3.) Question number three is? Answer1 Answer2 4.) Question num....
  26. Mail Form (php)
    This is a great email form script. (3)
    save this page as formmail.php Code: QUOTE $MailTo = "your email"; $MailSubject =
    "contact"; $MailHeader = "From: $s1"; $MailSent = "Put here the information you want to be shown
    after the message is sent."; if ($s1 == ""){ echo "You did not put your name ."; } else {
    $MailBody = "Name : $s1\n"; } if ($s2 == ""){ echo "You did not put your E-Mail ."; } else {
    $MailBody .= "Email : $s2\n"; } if ($s3 == ""){ } else { $MailBody .= "Message : $s3\n"; } {
    mail($MailTo, $MailSubject, $MailBody, $MailHeader); echo("$MailSent"); } ?>
    ------------------....
  27. Multiple Admin Login (php)
    This is a script that doesnt requre SQL (3)
    first off make a login.html page Code: QUOTE Admin Login Username: Password:
    then make a check.php page Code: QUOTE $admin1 = "admin1"; // first
    admin username $adm_pass1 = "password1"; // first admin password $admin2 = "admin2"; // second
    admin username $adm_pass2 = "password2"; // second admin password if(($username == $admin1 &&
    $password == $adm_pass1) || ($username == $admin2 && $password == $adm_pass2)){ echo
    "Congratulations " . $_POST . " You may now proceed to the admin area !"; } else { echo "Userna....

    1. Looking for , loops, script, planning, php
Similar
[phpbb] Member Last-visit Report Script - for phpbb2 databases
Fruity Loops Tutorials-arpiggeator - learn to use an arpiggeator giving stunning mellodys to bland chords
Fruity Loops Tutorials-trance Style Songs - How to create and use a profesional trance style bass mellody
Making A Song In Fruity Loops Part Three - part three precusion
Making A Song In Fruity Loops Part 2 - part 2 the second melody
How To Create A Song In Fruity Loops Using Vanguard - but you can use outhers
Background Image Swap Script - Change a Background Image based on clock time
Image Rotator Script (another One) - easy to implement
How To: Ip Configuration Script (win Xp) - If you travel a lot with your laptop, and need to switch between diff
Using An Actionscript In Flash For Loops
Php Script To Make A Link List - From the list of the Directory Files
Php Menu Bulding Script And Site Template - available for download
Script To Build A List Of Links - from filenames and h3 tags
Page Generation Time Script - A script to tell how long it took to generate
Verifying Email Addresses - Using a simple PHP script
Installing Ndstats! - The greatest Stats script of all time.
Random Quote Script
How To Use Trap17 Cgi Formmail - a built-in script in every hosting
[php] Simple Newsletter Script
Secure The Email Addresses On Your Website! - Wonderful script and useful! And working
E-mail Mailer Script 0.1 - useful for website visitors
Simple Php Counter Script - How to make a simple php counter script
Email Script/form With Php - how to make a simple email script using php
Php Guessing Script - Script game..
Php Quiz Script - Make quizzes for your site.
Mail Form (php) - This is a great email form script.
Multiple Admin Login (php) - This is a script that doesnt requre SQL

Searching Video's for , loops, script, planning, php
See Also,
advertisement


For ... Next Loops And Script Planning - My Fifth PHP Tutorial

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com