Programming Basics
  Home arrow Programming Basics arrow PHP Control Structures
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
JMSL Numerical Library 
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? 
PROGRAMMING BASICS

PHP Control Structures
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2003-04-08

    Table of Contents:
  • PHP Control Structures
  • Loops

  • 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


    PHP Control Structures


    (Page 1 of 2 )

    Like many other programming languages, PHP includes several different control structures that can be grouped into two different areas: conditional statements and loops. In the following tutorial, I will give you some examples of each and show you when to use them.

    By : Benjamin Bischoff

    Like many other programming languages, PHP includes several different control structures that can be grouped into two different areas: conditional statements and loops. In the following tutorial, I will give you some examples of each and show you when to use them. So let's start with the conditionals.

    If

    "If" is used whenever some PHP or HTML code needs to be executed based on one condition.

    <?php
    if ($myvariable == 1) print "Hello!";
    ?>

    This means "Print the string 'Hello!' if the variable $myvariable is equal to 1" (note the double equal signs!). If you want to execute more than one line of code, just use a code block:

    <?php
    if ($myvariable == 1)
    {
        print 
    "Hello!";
        
    $othervariable 2;
    }
    ?>

    In the above example, you tell PHP to "print the string 'Hello!' AND set the variable $othervariable to 2 if the variable $myvariable is equal to 1". You can even use if statements inside of other ifs if you like:

    <?php
    if ($myvariable == 1)
    {
        if (
    $othervariable == 2)
        {
            print 
    "Hello!";
        }
    }
    ?>

    This one checks if $myvariable equals 1. If this is true, it checks if $othervariable equals 2, and if this is also true, PHP will print "Hello!". There IS a better way to accomplish the above example with less code using other operators (I'll get to that in a short while) but let's first stick with other ways of using "if". So what if you want to execute other code if the given condition is NOT true? Well, just use "else":

    <?php
    if ($myvariable == 1)
    {
        print 
    "Hello!";
        
    $othervariable 2;
    }
    else
    {
        print 
    "Goodbye";
    }
    ?>

    Here, PHP will print the string "Goodbye" whenever $myvariable is something other than 1. If there are more than two code blocks you want to execute based on different conditions, you can use "elseif":

    <?php
    if ($myvariable == 1)
    {
        print 
    "Hello!";
        
    $othervariable 2;
    }
    elseif (
    $myvariable == 2)
    {
        print 
    "Have fun!";
    }
    else
    {
        print 
    "Goodbye";
    }
    ?>

    So now, PHP will check if $myvariable equals 1. If it isn't, it will check if $myvariable is 2, and if it is neither 1 or 2, PHP will print "Goodbye". You see that those constructs can be very long, for example if you want your script to act differently if $myvariable is 1, 2, 3, 4, etc. A shorter way to accomplish that is using the switch statement which I will discuss in a short while. But first, let me show you the different operators that can be used inside the most important control structures (so far we only used the double equal sign "==") and a funky new way of using "if".

    Operators
    ==          is equal
    &gt;           greater than
    &lt;           less than
    &gt;=          greater or equal
    &lt;=          less or equal
    !=          not equal
    &amp;&amp;          and (to connect two or more conditions)
    ||          or (to connect two or more conditions)
    !           not (negation)

    Let me give you a quick example for the "and", "or" and "not" operators:

    <?php
    if (($myvariable &lt10 &amp;&amp$myvariable &gt5) || !($othervariable 1))
    {
        print 
    "Yeah!";
    }
    ?>

    Can you see what that does? It means: "Print 'Yeah!' EITHER if $myvariable is less than 10 and greater than 5 OR if $othervariable is NOT equal to 1". Note that you can also write "$othervariable != 1" as the second condition.

    Now here's a slick little line of code for those of you who don't like long code fragments. Suppose you want to have an if statement that does this: "Check if $myvariable is 1. If that is true, change the value of $fruit to 'apple' else to 'banana'". Now that you know how to use if, you'd probably do it like this:

    <?php
    if ($myvariable == 1)
    {
        
    $fruit 'apple';
    }
    else
    {
        
    $fruit 'banana';
    }
    ?>

    There's another way, called the "ternary operator":

    <?php
    $fruit 
    = ($myvariable == 1) ? 'apple' 'banana';
    ?>

    That's it! Yes, I admit, it looks wild, but once you see how it works it's nice to use. You always use it like this:

    <?php
    $variable 
    =
    (
    condition) ? 'value_if_condition_is_true' 'value_if_condition_is_false'
    ?>

    Switch

    OK, time for "switch". Whenever you have many different code blocks that need to be executed based on different conditions of a variable, it's best to use "switch". An example? OK, here we go:

    <?php
    switch ($myvariable)
    {
        case 
    1:
            print 
    "One";
            break;
        case 
    2:
            print 
    "Two";
            break;
        case 
    3:
            print 
    "Three";
            break;
        default:
            print 
    "Other number";
    }
    ?>

    This one checks $myvariable and prints "One" if it's value is 1, "Two" if it's 2, "Three" if it's three and "Other Number" if it's something else (the "default" branch). But what about the "break;"? It stops the execution of the switch command! If you wrote the switch without the breaks, it would act differently. Check this out:

    <?php
    switch ($myvariable)
    {
        case 
    1:
            print 
    "One";
        case 
    2:
            print 
    "Two";
        case 
    3:
            print 
    "Three";
        default:
            print 
    "Other number";
    }
    ?>

    So let's say $myvariable equals 2. What will happen? Well, this script will print out: "TwoThreeOther number". Can you see why? Since $myvariable equals 2, the script prints out "Two". But because we didn't input the "break" commands, it executes all other lines inside the switch, too!

    More Programming Basics Articles
    More By Codewalkers


     

    PROGRAMMING BASICS ARTICLES

    - Loops and PHP Decision Making
    - Operators, Conditionals, and PHP Decision-Ma...
    - PHP Decision-Making
    - Coding
    - Server Statistics
    - Looping in PHP
    - Cookies in PHP
    - Working with text files
    - Beginning Object Oriented Programming in PHP
    - A Tour of Decision Making Structures in PHP
    - PHP Strings Primer
    - PHP Control Structures
    - Intro to Vim
    - Reading Directorys with PHP
    - An Overview of Arrays in PHP






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway