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:
- The $number variable sets it's value to 5.
- 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.
- 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:
- The $number variable sets it's value to 7.
- If the $number variable is equal to 5, the echo language construct displays that its not equal to 7. This statement is FALSE.
- If the $number variable is not equal to 9, the echo language construct displays it is not equal to 9. This statement is TRUE.
- 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:
- A pulldown form is created complete with method and action.
- The variable, $year is specified but the values are not set.
- 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.
- The "for" loop counts from the first value, 1950 and loops until it reaches the value or year, 2003.
- 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:
- An include file holds functions and database related information used by the script. The script connects to the database and selects the table.
- The query selects the distinct column and narrows it down to the specified rows of the table.
- The query values are set and the form is created using the column name derived from the SQL commands.
- 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:
- An array is created with the names of all 12 months.
- The form is constructed with the method and action.
- 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.
- The foreach construct extracts the values of the $month variable and produces the pulldown menu with each month's name.
- 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
developerWorks - FREE Tools! |
WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies. FREE! Go There Now!
|
|
|
|
This paper is about the critical role that a discipline called integrated requirements management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrating, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to try the IBM SOA Sandbox for people. The SOA Sandbox for people provides a trial environment with the necessary tooling and components required to enable consistent human and process interaction and collaboration, showing how you can improve user experience and business productivity. FREE! Go There Now!
|
|
|
|
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!
|
|
|
|
IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects. FREE! Go There Now!
|
|
|
|
Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications. FREE! Go There Now!
|
|
|
|
Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to try the IBM SOA Sandbox for process. The SOA Sandbox for process focuses on providing a trial environment with the necessary tooling and components required to gain a better understanding of business processes and how to best improve existing business processes to derive value quickly. FREE! Go There Now!
|
|
|
|
As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change. FREE! Go There Now!
|
|
|
|
The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |