eHow launches Android app: Get the best of eHow on the go.

How To

How to Create a for Statement in PHP

Contributor
By eHow Contributing Writer
(0 Ratings)

Conditional statements and loops are used to control the flow of a program. Like any other programming language, PHP has conditional statements and loops that trigger a different action when a condition is or is not met. One of these loop statements is the for statement. It is often the preferred loop statement, because its syntax is very compact and easy to read.

Difficulty: Easy
Instructions

Things You'll Need:

  • MySQL database server
  • Web server
  • PHP 5
  • PHP IDE

    Create a For Statement in PHP

  1. Step 1

    Define the variables you will use, then assign them an initial value:
    $count = 1;
    $total = 15;

  2. Step 2

    Write the expression that is to be evaluated when the loop begins. Note that this expression includes the action that must be performed if, at the end of the loop, the condition is still true. In this case, the action will increment the count variable:
    for ($count = 1; $count <= 10; $count++)

  3. Step 3

    Write the action that must be performed:
    {
    $total = $total + $count;
    echo "The total amount is $total
    ";
    }

  4. Check the Statement

  5. Step 1

    Double-check to make sure your code looks like this:
    $count = 1;
    $total = 15;
    for ($count = 1; $count <= 10; $count++)
    {
    $total = $total + $count;
    echo "The total amount is $total
    ";
    }

  6. Step 2

    Check for syntax errors and run the code. It must check to see if the count value is less than or equal to 10. When it is less than or equal to 10, its value will be incremented by 1, and then the new value will be used to calculate the total value. The loop continues while the count is less than or equal to 10.

Tips & Warnings
  • Write conditions that are true at the start. If the condition is false initially, the code block will not be executed at all.
  • Write conditions that will be met at some point, since a condition that will always be true will create an endless loop.
  • Pay attention to the syntax of the for statement you create, particularly if you have been programming in other languages and are fairly new to PHP.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

Demand Media
eHow_eHow Technology and Electronics