PHP
  Home arrow PHP arrow Using Control Structures in PHP
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Using Control Structures in PHP
By: Joel Philip
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 9
    2003-04-26

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    If you are a beginner to PHP, learning how to use control structures is a must. In this article Joel will assist you guys by providing coherent examples.

    Control structures are beneficial when coding in PHP. Many tasks can be accomplished with a small amount of coding but basic understanding on how to use them will solve many coding problems.

    What are Control Structures?

    Control Structures are often referred to as Conditionals, Branching or their familiar name, "Loops".

    Loops are great for retrieving information from databases, constructing tables and building dynamic pulldown menus.

    Here is a list of the different types of conditionals in PHP:

    • if/else
    • if/elseif/else
    • do/while
    • for
    • while
    • foreach

    The "if/else" conditional is the most commonly used statement in PHP coding.

    View the following code:

    <?php
    $number ='5';
    if($number =='3')
    {
    echo "The number is equal to 3";
    }
    else
    {
    echo "The number is equal to $number";
    }
    ?>

    Explanation of the code:

    1. The $number variable sets it's value to 5.
    2. If the $number variable is equal to 3 and becomes true the echo language construct displays the number is equal to 3. This statement is FALSE.
    3. Since the $number variable is really a value of 5 then it continues until it reaches the end of the conditional and displays The number is equal to 5. This statement is TRUE.

    Extending the conditional with the "if/elseif/else" statement would allow more options.

    View the following code:

    <?php
    $number = 7;
    if($number == '5')
    {
    echo "The number is not equal to 7";
    }
    elseif($number <> '9')
    {

    echo "The number is not equal to 9";
    }
    else
    {
    echo "The number is equal to $number";
    }
    ?>

    Explanation of the code:

    1. The $number variable sets it's value to 7.
    2. If the $number variable is equal to 5, the echo language construct displays that its not equal to 7. This statement is FALSE.
    3. If the $number variable is not equal to 9, the echo language construct displays it is not equal to 9. This statement is TRUE.
    4. The second conditional is the true statement of the script and the script terminates.

    Lets turn to "Loops" starting with the "for" conditional. The basic structure will continue looping until it resolves to FALSE.

    Here is an example of the "for" conditional that builds a pulldown menu with the years specified by the variable $x and the operand on the right.

    View the following code:

    <?php
    echo '<FORM ACTION="results.php" METHOD=post>';
    echo '<SELECT name=year>';
    echo"<OPTION VALUE=\"/\">Pick a year</OPTION>";
    for($x = 1950; $x <= 2003; $x++)
    {
    echo "<OPTION VALUE=$x>$x</OPTION>";
    }
    echo "</SELECT></FORM>";
    ?>

    Explanation of the code:

    1. A pulldown form is created complete with method and action.
    2. The variable, $year is specified but the values are not set.
    3. The top position on the pulldown menu is created using a forward slash to equal null and displays the "Pick a year" portion of the menu.
    4. The "for" loop counts from the first value, 1950 and loops until it reaches the value or year, 2003.
    5. The curly brace helps exit the loop and the closing tags finish the form.

    The "while" conditional helps loop through the tables of a database to retrieve the information and display onto a page.

    Here is an example of the "while" conditional creating a dynamic pulldown menu from a database:

    <?php
    include('config.php');
    dbconnect();
    $sql = SELECT DISTINCT(column_name) FROM $table_name;
    $result = @mysql_query($sql);
    echo "<FORM method=POST action=results.php>";
    echo "<SELECT NAME=column_name>";
    while($row = @mysql_fetch_array($result))
    {
    echo "<OPTION VALUE=\"$row[0]\">$row[0]</OPTION>";
    }
    echo "<INPUT TYPE=submit name=submit VALUE=\"Get Results\"></SELECT></FORM>";
    ?>

    Explanation of the code:

    1. An include file holds functions and database related information used by the script. The script connects to the database and selects the table.
    2. The query selects the distinct column and narrows it down to the specified rows of the table.
    3. The query values are set and the form is created using the column name derived from the SQL commands.
    4. The "while" loop creates the pulldown menu and the row values are set.

    Creating a pulldown menu that contains the months of the year would be bothersome using HTML. Using an array to hold the information and the "foreach()" statement helps speed things up in the long run.

    View the following code:

    <?php
    $month = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December");
    echo "<FORM METHOD=POST ACTION = results.php>";
    echo "<SELECT NAME=column_name >";
    echo"<OPTION VALUE=\"/\">Pick a Month</OPTION>";
    foreach($month as $MON)
    {
    echo "<OPTION VALUE=\"$MON\">$MON</OPTION>";
    }
    echo "</SELECT></FORM>";
    ?>

    Explanation of the code:

    1. An array is created with the names of all 12 months.
    2. The form is constructed with the method and action.
    3. The top position on the pulldown menu, labeled "Pick a Month" is created using a forward slash and it's value is set to null.
    4. The foreach construct extracts the values of the $month variable and produces the pulldown menu with each month's name.
    5. The curly brace helps exit the loop and the closing tags finish the form.

    I hope this gives you an understanding of Control Structures and how to use conditionals to your advantage.

    Happy coding and remember, "Let the code do the work".

    Copyright 2003 - Written by Joel Philip - http://www.phpcollege.com


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More PHP Articles
    More By Joel Philip

     

    IBM® developerWorks developerWorks - FREE Tools!


    Be the first to hear about i5/OS V6R1!

    Hold your calendar on January 30, 2008 for this free webcast on the new i5/OS. Rational's Enterprise Modernization products will be discussed at this webcast as they help to drive the application development environment for this new System i OS. <br />And learn how i5/OS will take you to the next step of efficient, resilient business processing. You will hear about the new i5/OS capabilities as it will be the most significant i5/OS release in years. If you cannot join the webcast on 1/30/08 you can still use this link to listen to the replay.<br />
    FREE! Go There Now!


    NEW! Best Practices: The Integrated Project and Portfolio Management Platform.

    Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan.
    FREE! Go There Now!


    NEW! "ebook: Exploring IBM SOA Technology & Practice

    Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    NEW! IBM Rational Systems Development e-Kit

    As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br />
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Krugle, developerWorks, and code search

    Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users.
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    PHP ARTICLES

    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP
    - PHP Frontend to ImageMagick
    - Using PEAR's mimeDecode Module
    - Incoming Mail and PHP







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT