PHP For the Absolute Beginner

Collapse
This is a sticky topic.
X
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    PHP For the Absolute Beginner

    This should you know at any time of day or night if you think that you consider yourself as Beginner, instead of Absolute Beginner.
    Have fun...

    (part 1)

    The Only Acronym You'll Ever Need

    If you're new to Web development, you could be forgiven for thinking that it consists of no more than a mass of acronyms, each one more indecipherable than the last. ASP, CGI, SOAP, XML, HTTP - the list seems never-ending, and the sheer volume of information on each of these can discourage the most avid programmer. But before you put on your running shoes and flee, there's a little secret you should know. To put together a cutting-edge Web site, chock full of all the latest bells and whistles, there's only one acronym you really need to know:

    PHP

    Now, while you have almost certainly heard of PHP, you may not be aware of just how powerful the language is, and how much it can do for you. Today, PHP has the enviable position of being the only open-source server-side scripting language that's both fun and easy to learn. This is not just advertising: recent surveys show that more than 16,000,000 Web sites use PHP as a server side scripting language, and the language also tops the list of most popular Apache modules.

    Why, you ask? The short answer: it's powerful, it's easy to use, and it's free. Extremely robust and scalable, PHP can be used for the most demanding of applications, and delivers excellent performance even at high loads. Built-in database support means that you can begin creating data-driven applications immediately, XML support makes it suitable for the new generation of XML-enabled applications, and the extensible architecture makes it easy for developers to use it as a framework to build their own custom modules. Toss in a great manual, a knowledgeable developer community and a really low price (can you spell f-r-e-e?) and you've got the makings of a winner!

    My goal in this series of tutorials is very simple: I'll be teaching you the basics of using PHP, and showing you why I think it's the best possible tool for Web application development today. I'll be making no assumptions about your level of knowledge, other than that you can understand basic HTML and have a sense of humor. And before you ask... Yes, this series covers both PHP 4 and PHP 5, with new PHP 5 features flagged for easy reference.

    Let's get going!
    The Right Environment

    PHP is typically used in combination with a Web server like Apache. Requests for PHP scripts are received by the Web server, and are handled by the PHP interpreter. The results obtained after execution are returned to the Web server, which takes care of transmitting them to the client browser. Within the PHP script itself, the sky's the limit - your script can perform calculations, process user input, interact with a database, read and write files... Basically, anything you can do with a regular programming language, you can do inside your PHP scripts.

    From the above, it is clear that in order to begin using PHP, you need to have a proper development environment set up.

    This series will focus on using PHP with the Apache Web server on Linux, but you can just as easily use PHP with Apache on Windows, UNIX and Mac OS. Detailed instructions on how to set up this development environment on each platform are available in the online manual, at PHP: Installation and Configuration - Manual - or you can just download a copy of PHP 5 from PHP: Hypertext Preprocessor and read the installation instructions.

    Go do that now, and come back when you've successfully installed and tested PHP.
    Start Me Up

    There's one essential concept that you need to get your mind around before we proceed further. Unlike CGI scripts, which require you to write code to output HTML, PHP lets you embed PHP code in regular HTML pages, and execute the embedded PHP code when the page is requested.

    These embedded PHP commands are enclosed within special start and end tags, like this:

    PHP Code:
    <?php 

    ... PHP code ... 

    ?>
    Here's a simple example that demonstrates how PHP and HTML can be combined:

    PHP Code:
    <html> 
    <head></head> 
    <body> 

    Agent: So who do you think you are, anyhow? 
    <br /> 

    <?php 
    // print output 
    echo 'Neo: I am Neo, but my people call me The One.'
    ?> 

    </body> 
    </html>
    Not quite your traditional "Hello, World" program... but then again, I always thought tradition was over-rated.
    Save the above script to a location under your Web server document root, with a .php extension, and browse to it.

    Look at the HTML source:

    Code:
    <html> 
    <head></head> 
    <body> 
    
    Agent: So who do you think you are, anyhow? 
    <br /> 
    Neo: I am Neo, but my people call me The One. 
    </body> 
    </html>
    What just happened? When you requested the script above, Apache intercepted your request and handed it off to PHP. PHP then parsed the script, executing the code between the <?php...?> marks and replacing it with the output of the code run. The result was then handed
    back to the server and transmitted to the client. Since the output contained valid HTML, the browser was able to render it for display to the user.

    A close look at the script will reveal the basic syntactical rules of PHP. Every PHP statement ends in a semi-colon. This convention is identical to that used in Perl, and omitting the semi-colon is one of the most common mistakes newbies make. That said, it is interesting to note that a semi-colon is not needed to terminate the last line of a PHP block. The PHP closing tag includes a semi-colon, therefore the following is perfectly valid PHP code:

    PHP Code:
    <?php 

    // print output 
    echo 'Neo: I am Neo, but my people call me The One.';

    ?>

    It's also possible to add comments to your PHP code, as I've done in the example above. PHP supports both single-line and multi-line comment blocks:

    PHP Code:
    <?php 

    // this is a single-line comment 

    /* and this is a 
    multi-line 
    comment */ 

    ?>
    Blank lines within the PHP tags are ignored by the parser. Everything outside the tags is also ignored by the parser, and returned as-is. Only the code between the tags is read and executed.
    A Case of Identity

    Variables are the bread and butter of every programming language... and PHP has them too. A variable can be thought of as a programming construct used to store both numeric and non-numeric data; the contents of a variable can be altered during program execution. Finally, variables can be compared with each other, and you - the programmer - can write code that performs specific actions on the basis of this comparison.

    PHP supports a number of different variable types: integers, floating point numbers, strings and arrays. In many languages, it's essential to specify the variable type before using it: for example, a variable may need to be specified as type integer or type
    array. Give PHP credit for
    a little intelligence, though: it automagically determines variable type by the context in which it is being used!

    Every variable has a name. In PHP, a variable name is preceded by a dollar ($) symbol and must begin with a letter or underscore, optionally followed by more letters, numbers and/or underscores. For example, $popeye,
    $one and
    $INCOME are all valid PHP variable names, while
    $123 and
    $48hrs are invalid.

    Note that variable names in PHP are case sensitive, so $me is different from
    $Me or
    $ME.

    Here's a simple example that demonstrates PHP's variables:

    PHP Code:
    <html> 
    <head></head> 
    <body> 

    Agent: So who do you think you are, anyhow? 
    <br /> 

    <?php 
    // define variables 
    $name 'Neo'
    $rank 'Anomaly'
    $serialNumber 1

    // print output 
    echo "Neo: I am <b>$name</b>, the <b>$rank</b>. You can call me by my serial number, <b>$serialNumber</b>."
    ?> 

    </body> 
    </html>
    Here, the variables $name,
    $rank and
    $serialNumber are first defined with string and numeric
    values, and then substituted in the echo() function call. The
    echo() function, along with the
    print() function, is commonly used to print data to the standard output device (here, the
    browser). Notice that I've included HTML tags within the call to echo(), and those have been
    rendered by the browser in its output. You can do this too. Really.
    An Equal Music

    To assign a value to a variable, you use the assignment operator: the = symbol. This is used to assign a value (the right side of the equation) to a variable (the left side). The value being assigned need not always be fixed; it could also be another variable, an expression, or even an expression involving other variables, as below:

    PHP Code:
    <?php 

    $age 
    $dob 15

    ?>
    Interestingly, you can also perform more than one assignment at a time. Consider the following example, which assigns three variables the same value simultaneously:

    PHP Code:
    <?php 

    $angle1 
    $angle2 $angle3 60

    ?>
    Not My Type

    Every language has different types of variable - and PHP is no exception. The language supports a wide variety of data types, including simple numeric, character, string and Boolean types, and more complex arrays and objects. Here's a quick list of the basic ones, with examples:
    Boolean: The simplest variable type in PHP, a Boolean variable, simply specifies a true or false value.

    PHP Code:
    <?php 

    $auth 
    true

    ?>
    Integer: An integer is a plain-vanilla whole number like 75, -95, 2000 or 1.

    PHP Code:
    <?php 

    $age 
    99

    ?>
    Floating-point: A floating-point number is typically a fractional number such as 12.5 or 3.141592653589. Floating point numbers may be specified using either decimal or scientific notation.

    PHP Code:
    <?php 

    $temperature 
    56.89

    ?>
    String: A string is a sequence of characters, like "hello" or "abracadabra". String values may be enclosed in either double quotes ("") or single quotes(''). (Quotation marks within the string itself can be "escaped" with a backslash (\) character.) String values enclosed in double quotes are automatically parsed for special characters and variable names; if these are found, they are replaced with the appropriate value. Here's an example:

    PHP Code:
    <?php 

    $identity 
    'James Bond'
    $car 'BMW'

    // this would contain the string "James Bond drives a BMW" 
    $sentence "$identity drives a $car"
    echo 
    $sentence

    ?>
    To learn more about PHP's data types, visit PHP: Types - Manual.
    Market Value

    If variables are the building blocks of a programming language, operators are the glue that let you build something useful with them. You've already seen one example of an operator - the assignment operator -, which lets you assign a value to a variable. Since PHP believes in spoiling you, it also comes with operators for arithmetic, string, comparison and logical operations.

    A good way to get familiar with operators is to use them to perform arithmetic operations on variables, as in the following example:

    PHP Code:
    <html> 
    <head> 
    </head> 
    <body> 

    <?php 

    // set quantity 
    $quantity 1000

    // set original and current unit price 
    $origPrice 100
    $currPrice 25

    // calculate difference in price 
    $diffPrice $currPrice $origPrice

    // calculate percentage change in price 
    $diffPricePercent = (($currPrice $origPrice) * 100)/$origPrice 

    ?>
     

    <table border="1" cellpadding="5" cellspacing="0"> 
    <tr> 
    <td>Quantity</td> 
    <td>Cost price</td> 
    <td>Current price</td> 
    <td>Absolute change in price</td> 
    <td>Percent change in price</td> 
    </tr> 
    <tr> 
    <td><?php echo $quantity ?></td> 
    <td><?php echo $origPrice ?></td> 
    <td><?php echo $currPrice ?></td> 
    <td><?php echo $diffPrice ?></td> 
    <td><?php echo $diffPricePercent ?>%</td> 
    </tr> 
    </table> 

    </body> 
    </html>
    Looks complex? Don't be afraid - it's actually pretty simple. The meat of the script is at the top, where I've set up variables for the unit cost and the quantity. Next, I've performed a bunch of calculations using PHP's various mathematical operators, and stored the results of those calculations in different variables. The rest of the script is related to the display of the resulting calculations in a neat table.

    If you'd like, you can even perform an arithmetic operation simultaneously with an assignment, by using the two operators together. The two code snippets below are equivalent:

    PHP Code:
    <?php 

    // this... 
    $a 5
    $a $a 10

    // ... is the same as this 
    $a 5
    $a += 10

    ?>
    If you don't believe me, try echoing them both.
    Stringing Things Along

    Why stop with numbers? PHP also allows you to add strings with the string concatenation operator, represented by a period (.). Take a look:

    PHP Code:
    <?php 

    // set up some string variables 
    $a 'the'
    $b 'games'
    $c 'begin'
    $d 'now'

    // combine them using the concatenation operator 
    // this returns 'the games begin now<br />' 
    $statement $a.' '.$b.' '.$c.' '.$d.'<br />'
    print 
    $statement

    // and this returns 'begin the games now!' 
    $command $c.' '.$a.' '.$b.' '.$d.'!'
    print 
    $command

    ?>
    As before, you can concatenate and assign simultaneously, as below:

    PHP Code:
    <?php 

    // define string 
    $str 'the'

    // add and assign 
    $str .= 'n'

    // str now contains "then" 
    echo $str

    ?>
    To learn more about PHP's arithmetic and string operators, visit PHP: Arithmetic Operators - Manual and PHP: String Operators - Manual.

    That's about it for this tutorial. You now know all about the basic building blocks and glue of PHP - its variables and operators. In Part Two of this series, I'll be using these fundamental concepts to demonstrate PHP's powerful form processing capabilities.

    Added after 5 minutes:

    (part 2)

    Not What You Expected

    In Part One of this series, I gave you a brief introduction to PHP, and how it fits into your Web application development environment. I also taught you the basics of PHP variables, and showed you how to add, multiply and concatenate them together.

    Now that you know the basics, it's time to focus in on one of PHP's nicer features - its ability to automatically receive user input from a Web form and convert it into PHP variables. If you're used to writing Perl code to retrieve form values in your CGI scripts, PHP's simpler approach is going to make you weep with joy. So get that handkerchief out, and scroll on down.
    Form...

    Forms have always been one of quickest and easiest ways to add interactivity to your Web site. A form allows you to ask customers if they like your products, casual visitors for comments on your site, and pretty girls for their phone numbers. And PHP can simplify the task of processing the data generated from a Web-based form substantially, as this first example demonstrates. This example contains two scripts, one containing an HTML form (named form.htm) and the other containing the form processing logic (message.php). Here's form.htm:


    Code:
    <html> 
    <head></head>
    <body> 
    <form action="message.php" method="post"> 
    Enter your message: <input type="text" name="msg" size="30"> 
    <input type="submit" value="Send"> 
    </form> 
    </body> 
    </html>
    The critical line in this page is the <form> tag


    <form action="message.php" method="post">
    ...
    </form>

    As you probably already know, the "action" attribute of the <form> tag specifies the name of
    the server-side script (message.php in this case) that will process the information entered into
    the form. The "method" attribute specifies how the information will be passed.
    ...And Function

    Now for the other half of the puzzle: the message.php script. This script reads the data
    submitted by the user and "does something with it". Here is message.php:


    PHP Code:
    <html> 
    <head></head>
    <body> 

    <?php 
    // retrieve form data 
    $input $_POST['msg']; 
    // use it 
    echo "You said: <i>$input</i>"
    ?> 

    </body> 
    </html>
    When you enter some data into form.htm (let's say "Boo"), and submit it, the form processor
    message.php will read it and display it to you ("You said: Boo"). Thus, whenever a form is
    submitted to a PHP script, all variable-value pairs within that form automatically become available for use within the script, through a special PHP container variable: $_POST. You can
    then access the value of the form variable by using its "name" inside the $_POST container, as I
    did in the script above.

    Obviously, PHP also supports the GET method of form submission. All you need to do is change the "method" attribute to "get", and retrieve values from $_GET instead of
    $_POST. The
    $_GET
    and $_POST variables are actually a special type of PHP animal called an array, which I'll be
    teaching you about shortly. Don't worry too much about it at the moment, just make sure you're comfortable with retrieving simple values from a form with PHP, and then scroll on down to learn about some more operators that are useful in this context.
    Operating With Extreme Caution

    Thus far, the scripts we've discussed have been pretty dumb. All they've done is add numbers and strings, and read back to you the data you typed in yourself - not exactly overwhelming. In order to add some intelligence to your scripts, you need to know how to construct what geeks call a "conditional statement" - a statement which lets your script perform one of a series of possible actions based on the result of a comparison test. And since the basis of a conditional statement is comparison, you first need to know how to compare two variables and determine whether they're identical or different.

    You've already seen some of PHP's arithmetic and string operators. However, the language also comes with operators designed specifically to compare two values: the so-called "comparison operators". Here's an example that demonstrates them in action:


    PHP Code:
    <?php 

    /* define some variables */
    $mean 9
    $median 10
    $mode 9

    // less-than operator 
    // returns true if left side is less than right 
    // returns true here 
    $result = ($mean $median); 
    print 
    "result is $result<br />"

    // greater-than operator 
    // returns true if left side is greater than right 
    // returns false here 
    $result = ($mean $median); 
    print 
    "result is $result<br />"

    // less-than-or-equal-to operator 
    // returns true if left side is less than or equal to right 
    // returns false here 
    $result = ($median <= $mode); 
    print 
    "result is $result<br />"

    // greater-than-or-equal-to operator 
    // returns true if left side is greater than or equal to right 
    // returns true here 
    $result = ($median >= $mode); 
    print 
    "result is $result<br />"

    // equality operator 
    // returns true if left side is equal to right 
    // returns true here 
    $result = ($mean == $mode); 
    print 
    "result is $result<br />"

    // not-equal-to operator 
    // returns true if left side is not equal to right 
    // returns false here 
    $result = ($mean != $mode); 
    print 
    "result is $result<br />"

    // inequality operator 
    // returns true if left side is not equal to right 
    // returns false here 
    $result = ($mean <> $mode); 
    print 
    "result is $result"

    ?>
    The result of a comparison test is always Boolean: either true (1) or false (0 - which doesn't print anything). This makes comparison operators an indispensable part of your toolkit, as you can use them in combination with a conditional statement to send a script down any of its multiple action paths.

    PHP 4.0 also introduced a new comparison operator, which allows you to test both for equality and type: the === operator. The following example demonstrates it:


    PHP Code:
    <?php 

    /* define two variables */
    $str '10'
    $int 10

    /* returns true, since both variables contain the same value */ 
    $result = ($str == $int); 
    print 
    "result is $result<br />"

    /* returns false, since the variables are not of the same type even though they have the same value */ 
    $result = ($str === $int); 
    print 
    "result is $result<br />"

    /* returns true, since the variables are the same type and value */ 
    $anotherInt 10
    $result = ($anotherInt === $int); 
    print 
    "result is $result"

    ?>
    Read more about PHP's comparison operators at PHP: Comparison Operators - Manual.
    A Question of Logic

    In addition to the comparison operators I used so liberally above, PHP also provides four logical operators, which are designed to group conditional expressions together. These four operators - logical AND, logical
    OR, logical
    XOR and logical
    NOT - are illustrated in the following example:


    PHP Code:
    <?php 

    /* define some variables */
    $auth 1
    $status 1
    $role 4

    /* logical AND returns true if all conditions are true */ 
    // returns true 
    $result = (($auth == 1) && ($status != 0)); 
    print 
    "result is $result<br />"

    /* logical OR returns true if any condition is true */ 
    // returns true 
    $result = (($status == 1) || ($role <= 2)); 
    print 
    "result is $result<br />"

    /* logical NOT returns true if the condition is false and vice-versa */ 
    // returns false 
    $result = !($status == 1); 
    print 
    "result is $result<br />"

    /* logical XOR returns true if either of two conditions are true, or returns false if both conditions are true */ 
    // returns false 
    $result = (($status == 1) xor ($auth == 1)); 
    print 
    "result is $result<br />"

    ?>
    Logical operators play an important role in building conditional statements, as they can be used to link together related conditions simply and elegantly. View more examples of how they can be used at PHP: Logical Operators - Manual.
    Older But Not Wiser

    Now that you've learnt all about comparison and logical operators, I can teach you about conditional statements. As noted earlier, a conditional statement allows you to test whether a specific condition is true or false, and perform different actions on the basis of the result. In PHP, the simplest form of conditional statement is the if() statement, which looks something
    like this:


    PHP Code:
    if (condition) { 
        do 
    this

    The argument to if()is a conditional expression, which evaluates to either true or false. If the
    statement evaluates to true, all PHP code within the curly braces is executed; if it does not, the code within the curly braces is skipped and the lines following the if() construct are executed.

    Let me show you how the if() statement works by combining it with a form. In this example,
    the user is asked to enter his or her age.


    Code:
    <html> 
    <head></head>
    <body> 
    <form action="ageist.php" method="post"> 
    Enter your age: <input name="age" size="2"> 
    </form> 
    </body> 
    </html>
    Depending on whether the entered age is above or below 21, a different message is displayed by the ageist.php script:


    PHP Code:
    <html> 
    <head></head>
    <body> 

    <?php 
    // retrieve form data 
    $age $_POST['age']; 
    // check entered value and branch 
    if ($age >= 21) { 
         echo 
    'Come on in, we have alcohol and music awaiting you!'

    if (
    $age 21) { 
         echo 
    "You're too young for this club, come back when you're a little older"

    ?> 

    </body> 
    </html>
    If Not This, Then What?

    In addition to the if() statement, PHP also offers the
    if-else construct, used to define a block
    of code that gets executed when the conditional expression in the if() statement evaluates
    as false.

    The if-else construct looks like this:


    PHP Code:
    if (condition) { 
        do 
    this
        } 
    else { 
        do 
    this

    This construct can be used to great effect in the last example: we can combine the two separate if()statements into a single
    if-else statement.


    PHP Code:
    <html> 
    <head></head>
    <body> 

    <?php 
    // retrieve form data 
    $age $_POST['age']; 
    // check entered value and branch 
    if ($age >= 21) { 
        echo 
    'Come on in, we have alcohol and music awaiting you!'
        } 
    else { 
        echo 
    "You're too young for this club, come back when you're a little older"

    ?> 

    </body> 
    </html>
    Spreading Confusion

    If the thought of confusing people who read your code makes you feel warm and tingly, you're going to love the ternary operator, represented by a question mark (?). This operator, which lets you make your conditional statements almost unintelligible, provides shortcut syntax for creating a single-statement if-else block. So, while you could do this:


    PHP Code:
    <?php 

    if ($numTries 10) { 
         
    $msg 'Blocking your account...'
        } 
    else { 
        
    $msg 'Welcome!'


    ?>
    You could also do this, which is equivalent (and a lot more fun):


    PHP Code:
    <?php 

    $msg 
    $numTries 10 'Blocking your account...' 'Welcome!'

    ?>
    PHP also lets you "nest" conditional statements inside each other. For example, this is perfectly valid PHP code:


    PHP Code:
    <?php 

    if ($day == 'Thursday') { 
        if (
    $time == '0800') { 
            if (
    $country == 'UK') { 
                
    $meal 'bacon and eggs'
            } 
        } 


    ?>
    Another, more elegant way to write the above is with a series of logical operators:


    PHP Code:
    <?php 

    if ($day == 'Thursday' && $time == '0800' && $country == 'UK') { 
        
    $meal 'bacon and eggs'


    ?>
    The Daily Special

    PHP also provides you with a way of handling multiple possibilities: the if-elseif-else
    construct. A typical if-elseif-else statement block would look like this:


    PHP Code:
    if (first condition is true) { 
        do 
    this
        } 
    elseif (
    second condition is true) { 
        do 
    this
        } 
    elseif (
    third condition is true) { 
        do 
    this
        } 
      ... and 
    so on ... 
    else { 
         do 
    this

    And here's an example that demonstrates how to use it:


    Code:
    <html> 
    <head></head>
    <body> 
    <h2>Today's Special</h2> 
    <p> 
    <form method="get" action="cooking.php"> 
    <select name="day"> 
    <option value="1">Monday/Wednesday 
    <option value="2">Tuesday/Thursday 
    <option value="3">Friday/Sunday 
    <option value="4">Saturday 
    </select> 
    <input type="submit" value="Send"> 
    </form> 
    </body> 
    </html>
    As you can see, this is simply a form which allows you to pick a day of the week. The real work is done by the PHP script cooking.php:


    PHP Code:
    <html> 
    <head></head>
    <body> 

    <?php 
    // get form selection 
    $day $_GET['day']; 
    // check value and select appropriate item 
    if ($day == 1) { 
        
    $special 'Chicken in oyster sauce'
        } 
    elseif (
    $day == 2) { 
        
    $special 'French onion soup'
        } 
    elseif (
    $day == 3) { 
        
    $special 'Pork chops with mashed potatoes and green salad'
        } 
    else { 
        
    $special 'Fish and chips'

    ?> 

    <h2>Today's special is:</h2> 
    <?php echo $special?> 
    </body> 
    </html>
    In this case, I've used the if-elseif-else control structure to assign a different menu special
    to each combination of days. Note that as soon as one of the if() branches within the block is
    found to be true, PHP will execute the corresponding code, skip the remaining if() statements
    in the block, and jump immediately to the lines following the entire if-elseif-else block.

    And that's it for now. To view more examples of conditional statements in action, visit PHP: Control Structures - Manual. In Part Three, I'll be bringing you more control structures, more operators and more strange and wacky scripts - so make sure you don't miss it!

    Added after 4 minutes:

    (part 3)

    Going Deeper

    If you've been paying attention, you remember that in Part Two I gave you a quick crash course in PHP's basic control structures and operators. I also showed you how PHP can be used to process the data entered into a Web form. In this tutorial, I'm going to delve deeper into PHP's operators and control structures, showing you two new operators, an alternative to the if-else() family of conditional statements, and some of PHP's more interesting loops. So
    keep reading... this is just about to get interesting!
    Switching Things Around

    An alternative to the if-else() family of control structures is PHP's
    switch-case() statement,
    which does almost the same thing. It looks like this:

    switch (decision-variable) {
    case first condition is true:
    do this!
    case second condition is true:
    do this!
    ... and so on...
    }

    Depending on the value of the decision variable, the appropriate case() block is executed. A
    default block can also be created, to handle all those occasions when the value of the decision
    variable does not match any of the listed case() conditions.

    I'll make this a little clearer by re-writing one of my earlier examples in terms of the switch()
    statement:

    PHP Code:
    <html>
    <head></head>
    <body>

    <?php

    // get form selection
    $day $_GET['day'];
    // check value and select appropriate item
    switch ($day) {
        case 
    1:
            
    $special 'Chicken in oyster sauce';
            break;
        case 
    2:
            
    $special 'French onion soup';
            break;
        case 
    3:
            
    $special 'Pork chops with mashed potatoes and green salad';
            break;
        default:
            
    $special 'Fish and chips';
            break;
    }

    ?>

    <h2>Today's special is:</h2>
    <?php echo $special ?>
    </body>
    </html>
    There are a couple of important keywords here:
    The break keyword is used to break out of the
    switch() statement block and move
    immediately to the lines following it.
    The default keyword is used to execute a default set of statements when the variable
    passed to switch() does not satisfy any of the conditions listed within the block.

    A common newbie mistake here is to forget the break at the end of every
    case() block.
    Remember that if you forget to break out of a case() block, PHP will continue executing the
    code in all the subsequent case() blocks it encounters.

    For more on the switch() statement, see http://www.php.net/manual/en/control-
    structures.switch.php.
    Creative Conditionals

    Normally, when creating and processing forms in PHP, you would place the HTML form in one file, and handle form processing through a separate PHP script. However, with the power of conditional statements at your disposal, you can combine both pages into one.

    How do you do this? Simple. All you need to do is assign a name to the form submit control,
    and then check whether the special $_POST container variable contains that name when the
    script first loads up. If it does, the form has already been submitted, and you can process the data; if it does not, that the user has not submitted the form and you therefore need to generate the initial, unfilled form. Thus, by testing for the presence or absence of this submit
    variable, a clever PHP programmer can use a single PHP script to generate both the initial form, and the output after it has been submitted, as appropriate.

    Here's a simple example:

    PHP Code:
    <html>
    <head></head>
    <body>

    <?php
    /* if the "submit" variable does not exist, the form has not been submitted - display initial page */
    if (!isset($_POST['submit'])) {
    ?>

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        Enter your age: <input name="age" size="2">
        <input type="submit" name="submit" value="Go">
        </form>

    <?php
        
    }
    else {
    /* if the "submit" variable exists, the form has been submitted - look for and process form data */
        // display result
        
    $age $_POST['age'];
        if (
    $age >= 21) {
            echo 
    'Come on in, we have alcohol and music awaiting you!';
            }
        else {
            echo 
    'You're too young for this clubcome back when you're a little older';
        }
    }
    ?>

    </body>
    </html>
    As you can see, the script contains two pages: the initial, empty form and the result page generated after hitting the submit button. In order to decide which page to display, the script
    first tests for the presence of the $_POST['submit'] variable. If it doesn't find it, it assumes that
    the form has yet to be submitted, and displays the initial list of days. Once the form has been submitted, the same script will be called to process the form input. This time, however, the $_POST['submit'] variable will be set, and so PHP will not display the initial page, but rather
    the page containing the result message.

    Note that for this to work, your submit button must have a value assigned to its "name"
    attribute, and you must check for that value in the primary conditional statement. And in case you were wondering, the $_SERVER array is a special PHP variable which always holds server
    information, including the path and name of the currently executing script.

    Next up, loops.
    One by One

    For those of you unfamiliar with the term, a loop is a control structure that enables you to repeat the same set of php
    statements or commands over and over again (the actual number of repetitions can be a number you specify, or depend on the fulfillment of one or more conditions).

    Now, last time out you saw a few comparison and logical operators, which help in building conditional statements. Since this segment of the tutorial is going to focus on loops, this is an appropriate time to introduce you to PHP's auto-increment and auto-decrement operators, which see a lot of use in this context.

    The auto-increment operator is a PHP operator designed to automatically increment the value of the variable it is attached to by 1. It is represented by two "plus" signs (++). This snippet of code should explain it:

    PHP Code:
    <?php

    // define $total as 10
    $total 10;
    // increment it
    $total++;
    // $total is now 11
    echo $total;

    ?>
    Thus, $total++ is functionally equivalent to
    $total = $total + 1.

    There's a corresponding auto-decrement operator (--), which does exactly the opposite:

    PHP Code:
    <?php

    // define $total as 10
    $total 10;
    // decrement it
    $total--;
    // $total is now 9
    echo $total;

    ?>
    These operators are frequently used in loops, to update the value of the loop counter, speaking of which...
    Being Square

    The first - and simplest - loop to learn in PHP is the so-called while() loop, which looks like this:

    while (condition is true) {
    do this!
    }

    In this case, so long as the condition specified evaluates as true - remember what you learned in Part Two? - the PHP statements within the curly braces will continue to execute. As soon as the condition becomes false, the loop will be broken and the statements following it will be executed.

    Here's a quick example which demonstrates the while() loop:

    Code:
    <html>
    <head></head>
    <body>
    <form action="squares.php" method="POST">
    Print all the squares between 1 and <input type="text" name="limit" size="4" maxlength="4">
    <input type="submit" name="submit" value="Go">
    </form>
    </body>
    </html>
    This is a simple form which asks the user to enter a number. When the form is submitted, the PHP script that is invoked should take this number and print the squares of all the numbers between 1 and the entered value. With a while() loop, this is simplicity itself:

    PHP Code:
    <html>
    <head></head>
    <body>

    <?php

    // set variables from form input
    $upperLimit $_POST['limit'];
    $lowerLimit 1;
    // keep printing squares until lower limit = upper limit
    while ($lowerLimit <= $upperLimit) {
        echo (
    $lowerLimit $lowerLimit).'&nbsp;';
        
    $lowerLimit++;
    }
    // print end marker
    echo 'END';

    ?>

    </body>
    </html>
    This script uses a while() loop to count forwards from 1 until the values of
    $lowerLimit and
    $upperLimit are equal.
    Loop First, Ask Questions Later

    The while() loop executes a set of statements while a specified condition is true. But what
    happens if the condition is true on the first iteration of the loop itself? In the previous example, if you were to enter the value 0in the form, the while() loop would not execute even once. Try
    it yourself and you'll see what I mean.

    If you're in a situation where you need to execute a set of statements *at least* once, PHP offers you the do-while() loop. Here's what it looks like:

    do {
    do this!
    } while (condition is true)

    Let's take a quick example to better understand the difference between while() and
    do-while():

    PHP Code:
    <?php

    $x 
    100;
    // while loop
    while ($x == 700) {
        echo 
    "Running...";
        break;
    }

    ?>
    In this case, no matter how many times you run this PHP script, you will get no output at all, since the value of $x is not equal to 700. But, if you ran this version of the script:

    PHP Code:
    <?php

    $x 
    100;
    // do-while loop
    do {
        echo 
    "Running...";
        break;
    } while (
    $x == 700);

    ?>
    you would see one line of output, as the code within the do() block would run once.

    Let's now revise the previous PHP script so that it runs at least once, regardless of what value is entered into the form:

    PHP Code:
    <html>
    <head></head>
    <body>

    <?php

    // set variables from form input
    $upperLimit $_POST['limit'];
    $lowerLimit 1;
    // keep printing squares until lower limit = upper limit
    do {
        echo (
    $lowerLimit $lowerLimit).'&nbsp;';
        
    $lowerLimit++;
    } while (
    $lowerLimit <= $upperLimit);
    // print end marker
    echo ' END';

    ?>

    </body>
    </html>
    Thus, the construction of the do-while() loop is such that the statements within the loop are
    executed first, and the condition to be tested is checked afterwards. This implies that the statements within the curly braces would be executed at least once.

    Read more about the while() and
    do-while() loops at http://www.php.net/manual/en/control-
    structures.while.php and PHP: do-while - Manual.
    Doing it by Numbers

    Both the while() and
    do-while() loops continue to iterate for as long as the specified
    conditional expression remains true. But what if you need to execute a certain set of statements a specific number of times - for example, printing a series of thirteen sequential numbers, or repeating a particular set of <td> cells five times? In such cases, clever
    programmers reach for the for() loop...

    The for() loop typically looks like this:


    for (initial value of counter; condition; new value of counter) {
    do this!
    }

    Looks like gibberish? Well, hang in there for a minute...the "counter" here is a PHP variable that is initialized to a numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop, the "condition" is tested. If it evaluates to true, the loop will execute once more and the counter will be appropriately incremented; if it evaluates to false, the loop will be broken and the lines following it will be executed instead.

    Here's a simple example that demonstrates how this loop can be used:

    PHP Code:
    <html>
    <head>
    <basefont face="Arial">
    </head>
    <body>

    <?php

    // define the number
    $number 13;
    // use a for loop to calculate tables for that number
    for ($x 1$x <= 10$x++) {
        echo 
    "$number x $x = ".($number $x)."<br />";
    }

    ?>

    </body>
    </html>
    The first thing I've done here is define the number to be used for the multiplication table. I've used 13 here - for no reason other than that it rhymes with "green".

    Next, I've constructed a for() loop with
    $x as the counter variable, initialized it to 1. and
    specified that the loop should run no more than 10 times. The auto-increment operator (discussed earlier) automatically increments the counter by 1 every time the loop is executed. Within the loop, the counter is multiplied by the number, to create the multiplication table, and echo() is used to display the result on the page.
    Turning the Tables

    As you just saw, a for() loop is a very interesting - and useful - programming construct. The
    next example illustrates its usefulness in a manner that should endear it to any HTML programmer.

    PHP Code:
    <html>
    <head></head>
    <body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Enter number of rows <input name="rows" type="text" size="4"> and columns <input name="columns" type="text" size="4"> <input type="submit" name="submit" value="Draw Table">
    </form>

    <?php

    if (isset($_POST['submit'])) {
        echo 
    "<table width = 90% border = '1' cellspacing = '5' cellpadding = '0'>";
        
    // set variables from form input
        
    $rows $_POST['rows'];
        
    $columns $_POST['columns'];
        
    // loop to create rows
        
    for ($r 1$r <= $rows$r++) {
            echo 
    "<tr>";
            
    // loop to create columns
            
    for ($c 1$c <= $columns;$c++) {
                echo 
    "<td>&nbsp;</td> ";
            }     echo 
    "</tr> ";
        }
        echo 
    "</table> ";
    }

    ?>

    </body>
    </html>
    As you'll see if you try coding the same thing by hand, PHP's for() loop just saved you a whole
    lot of work! And it looks good too - take a look at the source code of the dynamically generated table, and you'll see that it's nicely formatted, with line breaks at the end of every table cell and row. This magic is accomplished by forcing a carriage return with in every call to echo().

    For more examples of the for() loop in action, visit http://www.php.net/manual/en/control-structures.for.php
    .

    Loops are frequently used in combination with one of PHP's more complex data types, the animal known as the array. That's a whole topic in itself, and in fact I'm going to discuss it in detail in the next segment of this tutorial. Then I'm going to show you how arrays, loops and forms all work together to make the creation of complex Web forms as easy as eating pie. All that and more in Part Four!

    Added after 4 minutes:

    (part 4)

    A Big Mistake

    Having spent lots of time travelling around the outer landscape of PHP - learning all about control structures, operators and variables - you're probably bored. You might even be thinking of dropping out right now, and instead spending your time more constructively (or so you think) in front of the idiot box.

    That would be a big mistake. And when I say big, I mean humongous.

    You see, if you forego this segment of the tutorial for the dubious charms of Ally McBeal, you're going to miss out on one of PHP's coolest variable types. It's a little thing called an array, and I'm not exaggerating when I tell you that once you're on speaking terms with it, you're never going to look at a PHP script the same way again. But hey, don't take my word for it... toss that remote aside and come see for yourself!
    Fruity Pizza

    Thus far, the variables we've discussed contained only a single value, such as:


    PHP Code:
    <?php 

    $i 
    5;

    ?>
    However, array variables are a different kettle of fish altogether. An array is a complex variable that allows you to store multiple values in a single variable (which is handy when you need to store and represent related information). Think of the array variable as a "container" variable, which can contain one or more values. For example:


    PHP Code:
    <?php 

    // define an array
    $pizzaToppings = array('onion''tomato''cheese''anchovies''ham''pepperoni'); 
    print_r($pizzaToppings); 

    ?>
    Here, $pizzaToppings is an array variable, which contains the values
    'onion',
    'tomato',
    'cheese',
    'anchovies',
    'ham' and
    'pepperoni'. (Array variables are particularly useful for
    grouping related values together.)

    print_r() is a special function that allows you to take a sneak peek inside an array. It's more
    useful for debugging (finding out why your script doesn't work) than it is for display purposes, but I'll use it here so you can see what's going on under the surface. You do have your server running and your browser open, right?

    The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element 'onion', you would use the notation
    $pizzaToppings[0], while
    'anchovies' would be
    $pizzaToppings[3] - essentially, the array
    variable name followed by the index number enclosed within square braces.

    PHP also allows you to replace indices with user-defined "keys", in order to create a slightly different type of array. Each key is unique, and corresponds to a single value within the array.


    PHP Code:
    <?php 

    // define an array
    $fruits = array('red' => 'apple''yellow' => 'banana''purple' => 'plum''green' => 'grape'); 
    print_r($fruits); 

    ?>
    In this case, $fruits is an array variable containing four key-value pairs. (The
    => symbol is used
    to indicate the association between a key and its value.) In order to access the value 'banana',
    you would use the notation $fruits['yellow'], while the value
    'grape' would be accessible
    via the notation $fruits['green'].

    This type of array is sometimes referred to as a "hash" or "associative array". If you've ever used Perl, you'll see the similarities to the Perl hash variable.
    Eating Italian

    The simplest was to define an array variable is the array() function. Here's how:


    PHP Code:
    <?php 

    // define an array
    $pasta = array('spaghetti''penne''macaroni'); 

    ?>
    The rules for choosing an array variable name are the same as those for any other PHP variable: it must begin with a letter or underscore, and can optionally be followed by more letters, numbers and underscores.

    Alternatively, you can define an array by specifying values for each element in the index notation, like this:


    PHP Code:
    <?php 

    // define an array
    $pasta[0] = 'spaghetti'
    $pasta[1] = 'penne'
    $pasta[2] = 'macaroni'

    ?>
    If you're someone who prefers to use keys rather than default numeric indices, you might prefer the following example:


    PHP Code:
    <?php 

    // define an array
    $menu['breakfast'] = 'bacon and eggs'
    $menu['lunch'] = 'roast beef'
    $menu['dinner'] = 'lasagna'

    ?>
    You can add elements to the array in a similar manner. For example, if you wanted to add the element 'green olives' to the
    $pizzaToppings array, you would use something like this:


    PHP Code:
    <?php 

    // add an element to an array
    $pizzaToppings[3] = 'green olives'

    ?>
    In order to modify an element of an array, simply assign a new value to the corresponding scalar variable. If you wanted to replace 'ham' with
    'chicken', you'd use:


    PHP Code:
    <?php 

    // modify an array
    $pizzaToppings[4] = 'chicken'

    ?>
    You can do the same using keys. The following statement modifies the element with the key 'lunch' to a different value:


    PHP Code:
    <?php 

    // modify an array
    $menu['lunch'] = 'steak with mashed potatoes'

    ?>
    Push And Pull

    You can also add an element to the end of an existing array with the array_push() function:


    PHP Code:
    <?php 

    // define an array
    $pasta = array('spaghetti''penne''macaroni'); 

    // add an element to the end 
    array_push($pasta'tagliatelle'); 

    print_r($pasta); 

    ?>
    And you can remove an element from the end of an array using the interestingly-named array_pop() function.


    PHP Code:
    <?php 

    // define an array
    $pasta = array('spaghetti''penne''macaroni'); 

    // remove an element from the end 
    array_pop($pasta); 

    print_r($pasta); 

    ?>
    If you need to pop an element off the top of the array, you can use the array_shift() function:


    PHP Code:
    <?php 

    // define an array
    $pasta = array('spaghetti''penne''macaroni'); 

    // take an element off the top 
    array_shift($pasta); 

    print_r($pasta); 

    ?>
    And the array_unshift() function takes care of adding elements to the beginning of the array.


    PHP Code:
    <?php 

    // define an array
    $pasta = array('spaghetti''penne''macaroni'); 

    // add an element to the beginning 
    array_unshift($pasta'tagliatelle'); 

    print_r($pasta); 

    ?>
    The array_push() and
    array_unshift() functions don't work with associative arrays; to add
    elements to these arrays, it's better to use the $arr[$key] = $value notation to add new values to the array.

    The explode() function splits a string into smaller components, based on a user-specified
    delimiter, and returns the pieces as elements as an array.


    PHP Code:
    <?php 

    // define CSV string
    $str 'red, blue, green, yellow'

    // split into individual words 
    $colors explode(', '$str); 

    print_r($colors); 

    ?>
    To do the reverse, you can use the implode() function, which creates a single string from all
    the elements of an array by joining them together with a user-defined delimiter. Reversing the example above, we have:


    PHP Code:
    <?php 

    // define array
    $colors = array ('red''blue''green''yellow'); 

    // join into single string with 'and' 
    // returns 'red and blue and green and yellow' 
    $str implode(' and '$colors); 

    print 
    $str

    ?>
    Finally, the two examples below show how the sort() and
    rsort()functions can be used to
    sort an array alphabetically (or numerically), in ascending and descending order respectively:


    PHP Code:
    <?php 

    // define an array
    $pasta = array('spaghetti''penne''macaroni'); 

    // returns the array sorted alphabetically 
    sort($pasta); 
    print_r($pasta); 
    print 
    "<br />"

    // returns the array sorted alphabetically in reverse 
    rsort($pasta); 
    print_r($pasta); 

    ?>
    Looping the Loop

    So that takes care of putting data inside an array. Now, how about getting it out?

    Retrieving data from an array is pretty simple: all you need to do is access the appropriate element of the array using its index number. To read an entire array you simply loop over it, using any of the loop constructs you learned about in Part Three of this tutorial.

    How about a quick example?


    PHP Code:
    <html> 
    <head></head>
    <body> 
    My favourite bands are: 
    <ul> 

    <?php 

    // define array 
    $artists = array('Metallica''Evanescence''Linkin Park''Guns n Roses'); 
    // loop over it and print array elements 
    for ($x 0$x sizeof($artists); $x++) { 
        echo 
    '<li>'.$artists[$x]; 


    ?> 

    </ul> 
    </body> 
    </html>
    When you run this script, here's what you'll see:

    My favourite bands are:
    Metallica
    Evanescence
    Linkin Park
    Guns n Roses


    In this case, I've defined an array, and then used the for() loop to: run through it, extract the
    elements using the index notation, and display them one after the other.

    I'll draw your attention here to the sizeof() function. This function is one of the most important
    and commonly used array functions. It returns the size of (read: number of elements within) the array. It is mostly used in loop counters to ensure that the loop iterates as many times as there are elements in the array.

    If you're using an associative array, the array_keys() and
    array_values()functions come in
    handy, to get a list of all the keys and values within the array.


    PHP Code:
    <?php 

    // define an array
    $menu = array('breakfast' => 'bacon and eggs''lunch' => 'roast beef''dinner' => 'lasagna'); 

    /* returns the array ('breakfast', 'lunch', 'dinner') with numeric indices */ 
    $result array_keys($menu); 
    print_r($result); 
    print 
    "<br />"

    /* returns the array ('bacon and eggs', 'roast beef', 'lasagna') with numeric indices */ 
    $result array_values($menu); 
    print_r($result); 

    ?>
    What's That Noise?

    There is, however, a simpler way of extracting all the elements of an array. PHP 4.0 introduced a spanking-new loop type designed specifically for the purpose of iterating over an array: the foreach() loop. (It is similar in syntax to the Perl construct of the same name.) Here's what it
    looks like:


    foreach ($array as $temp) {
    do this!
    }

    A foreach() loop runs once for each element of the array passed to it as argument, moving
    forward through the array on each iteration. Unlike a for() loop, it doesn't need a counter or a
    call to sizeof(), because it keeps track of its position in the array automatically. On each run,
    the statements within the curly braces are executed, and the currently-selected array element is made available through a temporary loop variable.

    To better understand how this works, consider this rewrite of the previous example, using the foreach() loop:


    PHP Code:
    <html> 
    <head></head>
    <body> 
    My favourite bands are: 
    <ul> 

    <?php 

    // define array 
    $artists = array('Metallica''Evanescence''Linkin Park''Guns n Roses'); 
    // loop over it 
    // print array elements 
    foreach ($artists as $a) { 
        echo 
    '<li>'.$a


    ?> 

    </ul> 
    </body> 
    </html>
    Each time the loop executes, it places the currently-selected array element in the temporary variable $a. This variable can then be used by the statements inside the loop block. Since a
    foreach() loop doesn't need a counter to keep track of where it is in the array, it is lower-
    maintenance and also much easier to read than a standard for() loop. Oh yeah... and it also
    works with associative arrays, with no extra programming needed.
    Music for the Masses

    In addition to their obvious uses, arrays and loops also come in handy when processing forms in PHP. For example, if you have a group of related checkboxes or a multi-select list, you can use an array to capture all the selected form values in a single variable, to simplify processing. Consider the following example, which illustrates this:


    PHP Code:
    <html> 
    <head></head>
    <body> 

    <?php 
    // check for submit 
    if (!isset($_POST['submit'])) { 
        
    // and display form 
        
    ?> 

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> 
        <input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi 
        <input type="checkbox" name="artist[]" value="N'Sync">N'Sync 
        <input type="checkbox" name="artist[]" value="Boyzone">Boyzone 
        <input type="checkbox" name="artist[]" value="Britney Spears">Britney Spears 
        <input type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull 
        <input type="checkbox" name="artist[]" value="Crosby, Stills & Nash">Crosby, Stills & Nash 
        <input type="submit" name="submit" value="Select"> 
        </form> 

    <?php 
        

    else { 
        
    // or display the selected artists 
        // use a foreach loop to read and display array elements 
        
    if (is_array($_POST['artist'])) { 
            echo 
    'You selected: <br />'
            foreach (
    $_POST['artist'] as $a) { 
               echo 
    "<i>$a</i><br />"
                } 
            } 
        else { 
            echo 
    'Nothing selected'
        } 

    ?> 

    </body> 
    </html>
    When the above form is submitted, PHP will automatically create an array variable, and populate it with the items selected. This array can then be processed with a foreach() loop,
    and the selected items retrieved from it.

    You can do this with a multi-select list also, simply by using array notation in the select control's "name" attribute. Try it out for yourself and see... and make sure you tune in for the next PHP 101 tutorial, same time, same channel.

    Added after 5 minutes:

    (part 5)

    When you first started reading this series, I promised you that you'd have a whole lot of fun. If you're the cynical type, you may be feeling that I didn't keep my promise. After all, how much fun have you really had so far? All you've done is learn a bunch of theoretical rules, added and subtracted numbers from each other, learnt primitive decision-making and gone round and round in the circular funhouse of loops. Heck, if this wasn't a PHP tutorial, it would be kindergarten...

    I hear you.

    In this segment of our ongoing saga, I'm going to teach you how to do something that's definitely not for kids. It involves getting down and dirty with files on the disk: meeting them (shock!), reading their contents (shriek!) and (horror of horrors!) writing data to them. All of these exciting activities will take place under the aegis of PHP's very cool file manipulation API, which allows you to view and modify file attributes, read and list directory contents, alter file permissions, retrieve file contents into a variety of native data structures, and search for files based on specific patterns.

    Let's get started!
    Handle With Care

    I'll begin with something simple: opening a file and reading its contents. Let's assume that somewhere on your disk, hidden under /usr/local/stuff/that/should/be/elsewhere/recipes/, you have a text file containing the recipe for the perfect Spanish omelette. You now wish to read the contents of this file into a PHP script.

    In order to do this, there are three distinct steps to be followed:
    Open the file and assign it a file handle.
    Interact with the file, via its handle, and extract its contents into a PHP variable.
    Close the file.

    Here's a PHP script that does just that:


    PHP Code:
    <?php 

    // set file to read
    $file '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' or die('Could not open file!'); 
    // open file 
    $fh fopen($file'r') or die('Could not open file!'); 
    // read file contents 
    $data fread($fhfilesize($file)) or die('Could not read file!'); 
    // close file 
    fclose($fh); 
    // print file contents 
    echo $data

    ?>
    Run this script through your Web browser, and PHP should return the contents of the file.

    Now let me explain each of the three steps above in detail:
    Open the file and assign it a file handle

    PHP needs a file handle to read data from a file. This file handle can be created with the fopen() function, which accepts two arguments: the name and path to the file, and a string
    indicating the "mode" in which the file is to be opened ('r' for read).

    Three different modes are available for use with the fopen() function. Here's the list:

    'r' - opens a file in read mode

    'w' - opens a file in write mode, destroying existing file contents

    'a' - opens a file in append mode, preserving existing file contents
    Interact with the file via its handle and extract its contents into a PHP variable

    If the fopen() function is successful, it returns a file handle,
    $fh, which can be used for further
    interaction with the file. This file handle is used by the fread() function, which reads the file
    and places its contents into a variable.

    The second argument to fread() is the number of bytes to be read. You can usually obtain this
    information through the filesize() function, which - who'd have guessed it?!- returns the size
    of the file in bytes.
    Close the file

    This last step is not strictly necessary as PHP closes the file automatically once it reaches the end of the script, but it's a good habit to develop. Explicitly closing the file with fclose() has
    two advantages: it ties up loose ends in your script, and it wins you lots of good karma from the PHP community.

    You probably haven't see the die() function before, either. This function is mostly used as a
    primitive error-handling mechanism. In the event of a fatal error, such as the file path being invalid or the file permissions being such that PHP cannot read it, die() terminates script
    processing and optionally displays a user-specified error message indicating why it committed suicide.
    Different Strokes

    An alternative method of reading data from a file is the very cool file() function, which reads
    the entire file into an array (remember them?) with one line of code. Each element of the array then contains one line from the file. To display the contents of the file, simply iterate over the array in a foreach() loop and print each element.

    The following example demonstrates:


    PHP Code:
    <?php 

    // set file to read
    $file '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' or die('Could not read file!'); 
    // read file into array 
    $data file($file) or die('Could not read file!'); 
    // loop through array and print each line 
    foreach ($data as $line) { 
         echo 
    $line


    ?>
    In this example, the file() command opens the file, reads it into an array and closes the file -
    all in one, single, elegant movement. Each element of the array now corresponds to a line from the file. It's easy to print the file's contents now - just reach for that mainstay of array processing, the foreach() loop.

    Don't want the data in an array? Try the file_get_contents() function, new in PHP 4.3.0 and
    PHP 5.0, which reads the entire file into a string:


    PHP Code:
    <?php 

    // set file to read
    $file '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' 
    // read file into string 
    $data file_get_contents($file) or die('Could not read file!'); 
    // print contents 
    echo $data

    ?>
    Who am I kidding? I always use the one-line functions noted above instead of the three-line sequence of fopen(),
    fread() and
    fclose(). Laziness conquers all.
    When Laziness is a Virtue

    PHP also offers two very useful functions to import files into a PHP script: the include() and
    require()functions. These functions can be used to suck external files lock, stock and barrel
    into a PHP script, which is very handy if, for example, you have a modular application which has its code broken down across files in separate locations.

    The best way to understand the utility of the include() and
    require() functions is with an
    example. Assume that on your Web site you have a standard menu bar at the top of every page, and a standard copyright notice in the bottom. Instead of copying and pasting the header and footer code on each individual page, PHP gurus simply create separate files for the header and footer, and import them at the top and bottom of each script. This also makes a change to the site design easier to implement: instead of manually editing a gazillion files, you simply edit two, and the changes are reflected across your entire site instantaneously.

    Let's see a real live example of this in action. Create the header in one file, called header.php:


    PHP Code:
    <html> 
    <head> 
    <title><?php echo $page['title'];?></title> 
    </head> 
    <body> 
    <!-- top menu bar --> 
    <table width="90%" border="0" cellspacing="5" cellpadding="5"> 
    <tr> 
    <td><a href="#">Home</a></td> 
    <td><a href="#">Site Map</a></td> 
    <td><a href="#">Search</a></td> 
    <td><a href="#">Help</a></td> 
    </tr> 
    </table> 
    <!-- header ends -->  

    Next, create the footer with the copyright notice in a second file, footer.php: 


    <!-- footer begins --> 
    <br />
    <center>Your usage of this site is subject to its published <a href="tac.html">terms and conditions</a>. Data is copyright Big Company Inc, 1995-<?php echo date("Y"mktime()); ?></center> 
    </body> 
    </html>
    Finally, create a script to display the main content of your site, and include() the header and
    footer at appropriate places:


    PHP Code:
    <?php 

    // create an array to set page-level variables
    $page = array(); 
    $page['title'] = 'Product Catalog'
    /* once the file is imported, the variables set above will become available to it */ 

    // include the page header 
    include('header.php'); 

    ?> 

    <!-- HTML content here --> 

    <?php 

    // include the page footer 
    include('footer.php'); 

    ?>
    Now, when you run the script above, PHP will automatically read in the header and footer files, merge them with the HTML content, and display the complete page to you. Simple, isn't it?

    Notice that you can even write PHP code inside the files being imported. When the file is first read in, the parser will look for <?php...?> tags, and automatically execute the code inside it.
    (If you're familiar with JavaScript, you can use this feature to replicate functionality similar to that of the onLoad() page event handler in JavaScript.)

    PHP also offers the require_once() and
    include_once()functions, which ensure that a file
    which has already been read is not read again. This can come in handy if you have a situation in which you want to eliminate multiple reads of the same include file, either for performance reasons or to avoid corruption of the variable space.

    A quick note on the difference between the include() and
    require()functions: the
    require()
    function returns a fatal error if the named file cannot be found and halts script processing, while the include() function returns a warning but allows script processing to continue.
    Writing to Ma

    After everything you've just read, you've probably realized that reading a file is not exactly brain surgery. So let's proceed to something slightly more difficult - writing to a file.

    The steps involved in writing data to a file are almost identical to those involved in reading it: open the file and obtain a file handle, use the file handle to write data to it, and close the file. There are two differences: first, you must fopen() the file in write mode (
    'w' for write), and
    second, instead of using the fread() function to read from the file handle, use the
    fwrite()
    function to write to it. Take a look:


    PHP Code:
    <?php 

    // set file to write
    $file '/tmp/dump.txt'
    // open file 
    $fh fopen($file'w') or die('Could not open file!'); 
    // write to file 
    fwrite($fh"Look, Ma, I wrote a file! ") or die('Could not write to file'); 
    // close file 
    fclose($fh); 

    ?>
    When you run this script, it should create a file named dump.txt in
    /tmp, and write a line of text
    to it, with a carriage return at the end. Notice that double quotes are needed to convert into a carriage return.

    The fopen(),
    fwrite() and
    fread() functions are all binary-safe, which means you can use
    them on binary files without worrying about damage to the file contents. Read more about many of the issues related to binary-safe file manipulation on different platforms at PHP: fopen - Manual.

    If I've spoiled you by showing you the one-line shortcut functions for file reads, let me damage you further by introducing you to the file_put_contents() function, new in PHP 5.0, which
    takes a string and writes it to a file in a single line of code.


    PHP Code:
    <?php 

    // set file to write
    $filename '/tmp/dump.txt'
    // write to file 
    file_put_contents($filename"Look, Ma, I wrote a file! ") or die('Could not write to file'); 

    ?>
    Bear in mind that the directory in which you're trying to create the file must exist before you can write to it. Forgetting this important step is a common cause of script errors.
    Information is Power

    PHP also comes with a bunch of functions that allow you to test the status of a file - for example to find out whether it exists, whether it's empty, whether it's readable or writable, and whether it's a binary or text file. Of these, the most commonly used operator is the file_exists() function, which is used to test for the existence of a specific file.

    Here's an example which asks the user to enter the path to a file in a Web form, and then returns a message displaying whether or not the file exists:

    PHP Code:
    <html> 
    <head> 
    </head> 
    <body> 

    <?php 
    // if form has not yet been submitted 
    // display input box 
    if (!isset($_POST['file'])) { 
    ?> 

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
        Enter file path <input type="text" name="file"> 
        </form> 

    <?php 

    // else process form input 
    else { 
        
    // check if file exists 
        // display appropriate message 
        
    if (file_exists($_POST['file'])) { 
            echo 
    'File exists!'
            } 
        else { 
            echo 
    'File does not exist!'
        } 

    ?> 

    </body> 
    </html>

    There are many more such functions. Here's a brief list, followed by an example that builds on the previous one to provide more information on the file specified by the user.
    is_dir() - returns a Boolean indicating whether the specified path is a directory
    is_file() - returns a Boolean indicating whether the specified file is a regular file
    is_link() - returns a Boolean indicating whether the specified file is a symbolic link
    is_executable() - returns a Boolean indicating whether the specified file is executable
    is_readable()- returns a Boolean indicating whether the specified file is readable
    is_writable()- returns a Boolean indicating whether the specified file is writable
    filesize() - gets size of file
    filemtime() - gets last modification time of file
    filamtime() - gets last access time of file
    fileowner() - gets file owner
    filegroup() - gets file group
    fileperms() - gets file permissions
    filetype() - gets file type

    This script asks for a file name as input and uses the functions above to return information on it.

    PHP Code:
    <html> 
    <head> 
    </head> 
    <body> 

    <?php 
    /* if form has not yet been submitted, display input box */ 
    if (!isset($_POST['file'])) { 
    ?> 

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
        Enter file path <input type="text" name="file"> 
        </form> 

    <?php 

    // else process form input 
    else { 
        echo 
    'File name: <b>'.$_POST['file']  .'</b><br />'
        
    /* check if file exists and display appropriate message */ 
        
    if (file_exists($_POST['file'])) { 
            
    // print file size 
            
    echo 'File size: '.filesize($_POST['file']).' bytes<br />'
            
    // print file owner 
            
    echo 'File owner: '.fileowner($_POST['file']).'<br />'
            
    // print file group 
            
    echo 'File group: '.filegroup($_POST['file']).'<br />'
            
    // print file permissions 
            
    echo 'File permissions: '.fileperms($_POST['file']).'<br />'
            
    // print file type 
            
    echo 'File type: '.filetype($_POST['file']).'<br />'
            
    // print file last access time 
            
    echo 'File last accessed on: '.date('Y-m-d'fileatime($_POST['file'])).'<br />'
            
    // print file last modification time 
            
    echo 'File last modified on: '.date('Y-m-d'filemtime($_POST['file'])).'<br />'
            
    // is it a directory? 
            
    if (is_dir($_POST['file'])) { 
                echo 
    'File is a directory <br />'
            } 
            
    // is it a file? 
            
    if (is_file($_POST['file'])) { 
                echo 
    'File is a regular file <br />'
            } 
            
    // is it a link? 
            
    if (is_link($_POST['file'])) { 
                echo 
    'File is a symbolic link <br />'
            } 
            
    // is it executable? 
            
    if (is_executable($_POST['file'])) { 
                echo 
    'File is executable <br />'
            } 
            
    // is it readable? 
            
    if (is_readable($_POST['file'])) { 
                echo 
    'File is readable <br />'
            } 
            
    // is it writable? 
            
    if (is_writable($_POST['file'])) { 
                echo 
    'File is writable <br />'
            } 
        } 
        else { 
            echo 
    'File does not exist! <br />'
        } 

    ?> 

    </body> 
    </html>
    And here's what the output might look like:
    File name: /usr/local/apache/logs/error_log
    File size: 53898 bytes
    File owner: 0
    File group: 0
    File permissions: 33188
    File type: file
    File last accessed on: 2004-05-26
    File last modified on: 2004-06-20
    File is a regular file
    File is readable

    Breaking Eggs

    So now you know how to read a file, write to it, and test its status. Let's look at some examples of what you can do with this new-found power.

    Let's go back to my Spanish omelette recipe. Let's suppose I'm feeling generous, and I decide that I'd like to hear what people really think about my culinary skills. Since I have a bunch of recipes that I'd like to share with people, and since they all look something like this:
    SPANISH OMELETTE
    INGREDIENTS:
    - 1 chopped onion
    - 1 chopped tomato
    - 1/2 chopped green pepper
    - 4 beaten eggs
    - Salt and pepper to taste
    METHOD:
    1. Fry onions in a pan
    2. Pour beaten eggs over onions and fry gently
    3. Add tomatoes, green pepper, salt and pepper to taste
    4. Serve with toast or bread


    I need a quick way to convert them all into HTML so that they look presentable on my Web site. We've already established that I'm lazy, so fuggedaboutme re-creating the recipes in HTML. Instead, I'll have PHP do the heavy lifting for me:

    PHP Code:
    <html> 
    <head></head>
    <body> 

    <?php 
    // read recipe file into array 
    $data file('/usr/local/stuff/that/should/be/elsewhere/omelette.txt') or die('Could not read file!'); 
    /* first line contains title: read it into variable */ 
    $title $data[0]; 
    // remove first line from array 
    array_shift($data); 
    ?> 

    <h2><?php echo $title?></h2> 

    <?php 
    /* iterate over content and print it */ 
    foreach ($data as $line) { 
        echo 
    nl2br($line); 

    ?> 

    </body> 
    </html>
    I've used the file() function to read the recipe into an array, and assign the first line (the title)
    to a variable. That title is then printed at the top of the page. Since the rest of the data is fairly presentable as is, I can simply print the lines to the screen one after the other. Line breaks are automatically handled for me by the extremely cool nl2br() function, which converts regular
    text linebreaks into the HTML equivalent, the <br /> tag. The end result: an HTML-ized version
    of my recipe that the world can marvel at. Take a look:

    Code:
    <html>
    <head></head><body>
    
    <h2>SPANISH OMELETTE
    </h2>
    INGREDIENTS:<br />
    - 1 chopped onion<br />
    - 1 chopped tomato<br />
    - 1/2 chopped green pepper<br />
    - 4 beaten eggs<br />
    
    - Salt and pepper to taste<br />
    METHOD:<br />
    1. Fry onions in a pan<br />
    2. Pour beaten eggs over onions and fry gently<br />
    3. Add tomatoes, green pepper, salt and pepper to taste<br />
    4. Serve with toast or bread<br />
    
    </body>
    </html>

    If the elegance and creative simplicity of my Spanish omelette recipe has left you speechless, I'm not surprised - many people feel that way. Until you get your voice back: Ciao... and make sure you come back to work through Part Six of PHP 101, which discusses creating your own reusable functions.

    Added after 4 minutes:

    (part 6)

    A Little Knowledge

    If you've been taking your regular dose of PHP 101, you know now enough about PHP to write simple programs of your own. However, these programs will be "procedural" or linear - the statements in them will be executed sequentially, one after another - simply because that's the only programming style I've used so far.

    You know what they say about a little knowledge being a dangerous thing... as your PHP scripts become more and more complex, it's only a matter of time before you bump your head against the constraints of the procedural method, and begin looking for a more efficient way of structuring your PHP programs.

    That's where Part Six of PHP 101 comes in. In this tutorial I'm going to introduce you to a new way of doing things, where code doesn't run in a straight line, but twists, leaps and bounds across the landscape of your script. Most of this activity is accomplished through a programming construct called a "function", and this tutorial teaches you how to build them (once), use them (many times), pass them arguments and have them return values, and generally make your scripts more compact, efficient and maintainable.
    In Plain English

    Ask a geek to define the term "function", and he'll probably mumble something about a function being "a block of statements that can be grouped together as a named entity." Since this is a tutorial on PHP, not an introductory course in Greek, I'll translate that for you: a function is simply a set of program statements which perform a specific task, and which can be "called", or executed, from anywhere in your program.

    Every programming language comes with its own built-in functions, and typically also allows developers to define their own functions. For example, if I had a profit statement for the year on my desk, and I wanted to inflate each number by 35%, I could call my neighborhood accounting firm and get them to do it for me... or I could write a simple PHP function called cheatTheShareholders() and have it do the work for me (it's faster, plus PHP doesn't bill by the
    hour).

    There are three important reasons why functions are a Good Thing™. First: user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug. Second: functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program. And third: functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition). Functions thus save time, money and electrons... and I know the electrons at least will thank you!
    Monday Morning Blues

    To see how a function works, look at the following example:

    PHP Code:
    <?php 

    // define a function 
    function myStandardResponse() { 
        echo 
    "Get lost, jerk!<br /><br />"


    // on the bus 
    echo "Hey lady, can you spare a dime? <br />"
    myStandardResponse(); 

    // at the office 
    echo "Can you handle Joe's workload, in addition to your own, while he's in Tahiti for a month? You'll probably need to come in early and work till midnight, but we are confident you can handle it. Oh, and we can't pay you extra because of budgetary constraints...<br />"
    myStandardResponse(); 

    // at the party 
    echo "Hi, haven't I seen you somewhere before?<br />"
    myStandardResponse(); 

    ?>

    Here's what the output might look like:
    Hey lady, can you spare a dime?
    Get lost, jerk!

    Can you handle Joe's workload, in addition to your own, while he's in Tahiti for a month?
    You'll probably need to come in early and work till midnight, but we are confident you can
    handle it. Oh, and we can't pay you extra because of budgetary constraints...
    Get lost, jerk!

    Hi, haven't I seen you somewhere before?
    Get lost, jerk!
    (Sure it's rude, but it does demonstrate how a function allows you to reuse pieces of code.)


    The first thing I've done in the script above is define a new function, with the function
    keyword. This keyword is followed by the name of the function, which in this case is myStandardResponse(). All the program code attached to that function is then placed within a
    pair of curly braces - and this program code can contain loops, conditional statements, calls to other user-defined functions, or calls to other PHP functions.

    Of course, defining a function is only half of the puzzle; for it to be of any use at all, you need to "invoke" it. In PHP, as in a million other languages, this is accomplished by calling the function by its name, as I've done in the example above. Calling a user-defined function is identical to calling a built-in PHP function like echo() or
    explode().

    Here's the typical format for a function:

    function function_name (optional function arguments) {
    statement 1...
    statement 2...
    .
    .
    .
    statement n...
    }
    Having an Argument... or Two

    Functions like the one you saw in the previous section print the same value every time you invoke them. While this is interesting the first six times, it can get boring on the seventh. What we need to do, to make these boring, unintelligent functions a little more exciting, is get them to return a different value each time they are invoked.

    Enter arguments.

    Arguments work by using a placeholder to represent a certain variable within a function. Values for this variable are provided to the function at run-time from the main program. Since the input to the function will differ at each invocation, so will the output.

    To see how this works, look at the following function, which accepts a single argument and then prints it back after a calculation:

    PHP Code:
    <?php 

    // define a function 
    function getCircumference($radius) { 
        echo 
    "Circumference of a circle with radius $radius is ".sprintf("%4.2f", ($radius pi()))."<br />"


    // call a function with an argument 
    getCircumference(10); 

    // call the same function with another argument 
    getCircumference(20); 

    ?>
    In this example, when the getCircumference() function is called with an argument, the
    argument is assigned to the placeholder variable $radius within the function, and then acted
    upon by the code within the function definition.

    It's also possible to pass more than one argument to a function. This is done using a comma-separated list, as the following example shows:

    PHP Code:
    <?php 

    // define a function 
    function changeCase($str$flag) { 
        
    /* check the flag variable and branch the code */ 
        
    switch($flag) { 
            case 
    'U'
                print 
    strtoupper($str)."<br />"
                break; 
            case 
    'L'
                print 
    strtolower($str)."<br />"
                break; 
            default: 
                print 
    $str."<br />"
                break; 
        } 


    // call the function 
    changeCase("The cow jumped over the moon""U"); 
    changeCase("Hello Sam""L"); 

    ?>
    Here, depending on the value of the second argument, program flow within the function moves to the appropriate branch and manipulates the first argument.

    Note that there is no requirement to specify the data type of the argument being passed to a function. Since PHP is a dynamically-typed language, it automatically identifies the variable type and acts on it appropriately.
    Circles in the Sand

    The functions on the previous page simply printed their output to the screen. But what if you want the function to do something else with the result? Well, in PHP, you can have a function return a value, such as the result of a calculation, to the statement that called it. This is done using a return statement within the function, as shown below:

    PHP Code:
    <?php 

    // define a function 
    function getCircumference($radius) { 
        
    // return value 
        
    return ($radius pi()); 


    /* call a function with an argument and store the result in a variable */ 
    $result getCircumference(10); 

    /* call the same function with another argument and print the return value */ 
    print getCircumference(20); 

    ?>
    Here, the argument passed to the getCircumference() function is processed, and the result is
    returned to the main program, where it may be captured in a variable, printed, or dealt with in other ways.

    You can even use the result of a function inside another function, as illustrated in this minor revision of the example above:

    PHP Code:
    <?php 

    // define a function 
    function getCircumference($radius) { 
    // return value 
        
    return ($radius pi()); 


    // print the return value after formatting it 
    print "The answer is ".sprintf("%4.2f"getCircumference(20)); 

    ?>
    Return values need not be numbers or strings alone: a function can just as easily return an array (remember them?), as demonstrated in the following example:

    PHP Code:
    <?php 

    /* define a function that can accept a list of email addresses */ 
    function getUniqueDomains($list) { 
        
    /* iterate over the list, split addresses and add domain part to another array */ 
        
    $domains = array(); 
        foreach (
    $list as $l) { 
            
    $arr explode("@"$l); 
            
    $domains[] = trim($arr[1]); 
        } 
        
    // remove duplicates and return 
        
    return array_unique($domains); 


    // read email addresses from a file into an array 
    $fileContents file("data.txt"); 

    /* pass the file contents to the function and retrieve the result array */ 
    $returnArray getUniqueDomains($fileContents); 

    // process the return array 
    foreach ($returnArray as $d) { 
        print 
    "$d, "


    ?>
    Assuming the file looked like this,
    test@test.com
    a@x.com
    zooman@deeply.bored.org
    b@x.com
    guess.me@where.ami.net
    testmore@test.com
    the output of the script above would look like this:
    test.com, x.com, deeply.bored.org, where.ami.net,
    Note that the return statement terminates program execution inside a function.
    Marching Order

    The order in which arguments are passed to a function can be important. The following example requires that the name is passed as the first argument, and the place as the second.

    PHP Code:
    <?php 

    // define a function 
    function introduce($name$place) { 
        print 
    "Hello, I am $name from $place"


    // call function 
    introduce("Moonface""The Faraway Tree"); 

    ?>
    This is the output:
    Hello, I am Moonface from The Faraway Tree
    In this example, if you reversed the order in which arguments were passed to the function, this is what you'd see:
    Hello, I am The Faraway Tree from Moonface
    And look what happens if you forget to pass a required argument altogether:
    Warning: Missing argument 2 for introduce() in xx.php on line 3
    Hello, I am Moonface from
    In order to avoid such errors, PHP allows you to specify default values for all the arguments in a user-defined function. These default values are used if the function invocation is missing some arguments. Here's an example:


    PHP Code:
    <?php 

    // define a function 
    function introduce($name="John Doe"$place="London") { 
        print 
    "Hello, I am $name from $place"


    // call function 
    introduce("Moonface"); 

    ?>
    In this case the output would be:
    Hello, I am Moonface from London

    Notice that the function has been called with only a single argument, even though the function definition requires two. However, since default values are present for each argument in the function, the missing argument is replaced by the default value for that argument, and no error is generated.
    The Amazing Shrinking Argument List

    All the examples on the previous page have one thing in common: the number of arguments in the function definition is fixed. However, PHP 4.x also supports variable-length argument lists, by using the func_num_args() and
    func_get_args() commands. For want of a better name,
    these functions are called "function functions". Try wrapping your tongue around that while you look at the next example, which demonstrates how they can be used:

    PHP Code:
    <?php 

    // define a function 
    function someFunc() { 
        
    // get the arguments 
        
    $args func_get_args(); 
         
        
    // print the arguments 
        
    print "You sent me the following arguments:"
        foreach (
    $args as $arg) { 
            print 
    $arg "
        } 
        print 
    "<br />"


    // call a function with different arguments 
    someFunc("red""green""blue"); 
    someFunc(1"soap"); 

    ?>
    Hmmm... if you're sneaky, you might have tried to pass someFunc() an array, and found that
    instead of displaying the elements of the array, it simply said "Array". You can fix this by adding a quick test for array arguments inside the function, as in this rewrite:

    PHP Code:
    <?php 

    // define a function 
    function someFunc() { 
        
    // get the number of arguments passed 
        
    $numArgs func_num_args(); 
         
    // get the arguments 
        
    $args func_get_args(); 
         
        
    // print the arguments 
        
    print "You sent me the following arguments: "
        for (
    $x 0$x $numArgs$x++) { 
            print 
    "<br />Argument $x: "
            
    /* check if an array was passed and, if so, iterate and print contents */ 
            
    if (is_array($args[$x])) { 
                print 
    " ARRAY "
                foreach (
    $args[$x] as $index => $element) { 
                    print 
    $index => $element "
                } 
            } 
            else { 
                print 
    $args[$x] "
            } 
        } 


    // call a function with different arguments 
    someFunc("red""green""blue", array(4,5), "yellow"); 

    ?>
    Going Global

    Let's now talk a little bit about the variables used within a function, and their relationship with variables in the outside world. Usually, the variables used within a function are "local" - meaning that the values assigned to them, and the changes made to them, are restricted to the function space alone.

    Consider this simple example:

    PHP Code:
    <?php 

    // define a variable in the main program 
    $today "Tuesday"

    // define a function 
    function getDay() { 
        
    // define a variable inside the function 
        
    $today "Saturday"
        
    // print the variable 
        
    print "It is $today inside the function<br />"


    // call the function 
    getDay(); 

    // print the variable 
    print "It is $today outside the function"

    ?>
    When you run this script, here is what you will see:
    It is Saturday inside the function
    It is Tuesday outside the function
    In other words, the variable inside the function is insulated from the identically-named variable in the main program. Variables inside a function are thus aptly called "local" variables because they only exist within the function in which they are defined.


    The reverse is also true: variables defined inside a function cannot be "seen" outside it. To illustrate, take a look at the next example and its output (or the lack of it):

    PHP Code:
    <?php 

    // define a function 
    function getDay() { 
        
    // define a variable inside the function 
        
    $today "Saturday"


    getDay(); 
    print 
    "Today is $today"

    ?>
    Here is the output:
    Today is
    Depending on the error_reporting you have set up in php.ini, you might also see an error message:
    Notice: Undefined variable: today in x1.php on line 10

    However, I didn't say this can't be overcome. To have variables within a function accessible from outside it (and vice-versa), all you need to do is first declare them "global" with the - you guessed it! - global keyword.


    Here is a rewrite of the earlier example, this time declaring the $today variable global:

    PHP Code:
    <?php 

    // define a variable in the main program 
    $today "Tuesday"

    // define a function 
    function getDay() { 
        
    // make the variable global 
        
    global $today
         
        
    // define a variable inside the function 
        
    $today "Saturday"
        
    // print the variable 
        
    print "It is $today inside the function<br />"


    // print the variable 
    print "It is $today before running the function<br />"

    // call the function 
    getDay(); 

    // print the variable 
    print "It is $today after running the function"

    ?>
    And here is the output:
    It is Tuesday before running the function
    It is Saturday inside the function
    It is Saturday after running the function
    Thus, once a variable is declared global, it is available at the global level, and can be manipulated both inside and outside a function.


    PHP also comes with so-called superglobal variables - variables that are always available, regardless of whether you're inside a function or outside it. You've already seen some of these special variables in action: the $_SERVER,
    $_POST and
    $_GET variables are all superglobals, which
    is why you can access things like the currently-executing script's name or form values even inside a function.

    Superglobals are a Good Thing™, because they're always there when you need them, and you don't need to jump through any hoops to use the data stored inside them. Read more about superglobals and variable scope at PHP: Predefined Variables - Manual and PHP: Variable scope - Manual.
    Checking References

    Any discussion about variables in and out of functions would be incomplete without some mention of the difference between "passing by reference" and "passing by value". So far, all the examples you've seen have involved passing arguments to a function "by value" - meaning that a copy of the variable was passed to the function, while the original variable remained untouched. However, PHP also allows you to pass "by reference" - meaning that instead of passing a value to a function, you pass a reference to the original variable, and have the function act on that instead of a copy.

    Confusing? Well, this is probably easier to understand with an example. Let's start with this:

    PHP Code:
    <?php 

    // create a variable 
    $today "Saturday"

    // function to print the value of the variable 
    function setDay($day) { 
        
    $day "Tuesday"
        print 
    "It is $day inside the function<br />"


    // call function 
    setDay($today); 

    // print the value of the variable 
    print "It is $today outside the function"

    ?>
    You've already seen this before, and you already know what the output is going to say:
    It is Tuesday inside the function
    It is Saturday outside the function
    This is because when the getDay() function is invoked, it passes the value "Saturday" to the
    function ("passing by value"). The original variable remains untouched; only its content is sent to the function. The function then acts on the content, modifying and displaying it.


    Now, look at how "passing by reference" works:

    PHP Code:
    <?php 

    // create a variable 
    $today "Saturday"

    // function to print the value of the variable 
    function setDay(&$day) { 
        
    $day "Tuesday"
        print 
    "It is $day inside the function<br />"


    // call function 
    setDay($today); 

    // print the value of the variable 
    print "It is $today outside the function"

    ?>
    Notice the ampersand (&) before the argument in the function definition. This tells PHP to use the variable reference instead of the variable value. When such a reference is passed to a function, the code inside the function acts on the reference, and modifies the content of the original variable (which the reference is pointing to) rather than a copy. If you then try retrieving the value of the original variable outside the function, it returns the modified value:
    .
    It is Tuesday inside the function
    It is Tuesday outside the function
    Now you understand why I said no discussion about variables would be complete without mentioning the two ways of passing variables. This, of course, is what the global keyword
    does inside a function: use a reference to ensure that changes to the variable inside the function also reflect outside it. The PHP manual puts it best when it says "...when you declare a variable as global $var you are in fact creating a reference to a global variable". For more
    examples, read all about references at PHP: Documentation.


    And that just about concludes this tutorial. This time you've taken a big step towards better software design by learning how to abstract parts of your PHP code into reusable functions. You now know how to add flexibility to your functions by allowing them to accept different arguments, and how to obtain one (or more) return values from them. Finally, you've learned a little bit about how PHP treats variables inside and outside functions.

    In Part Seven, I'll be showing you how to group related functions together into classes, and also telling you all about the cool new features in the PHP 5 object model. You definitely don't want to miss that one!

    zend.com

    Also you can use this E-Books for further learning.
    Last edited by arnage; 08.08.11, 17:19.
    <!DOCTYPE html PUBLIC "-//WAPFORUM.RS

    #2
    I just saw it, sticky thread. Thanks!
    <!DOCTYPE html PUBLIC "-//WAPFORUM.RS

    Comment


      #3
      very well said. nice tutorial, good for beginners

      http://wapx.amob.com
      Applications, Games, Wallpapers, Ringtones, Videos, Themes, Screensaver and More!!!

      Comment


        #4
        Originally posted by arnage View Post
        I just saw it, sticky thread. Thanks!
        I thot you were writing this ) ! anyway .. the one who wrote it , ... took him an age and a half to do that ! (hope not) {}{}{}
        This is ten percent luck, twenty percent skill
        Fifteen percent concentrated power of will
        Five percent pleasure, fifty percent pain

        And a hundred percent reason to remember the name!

        Comment


          #5
          its awesome for everybody who is in mood to learn php but they do not have a clue about it. must be thanked by all members of forum as can see it took your time to make this post (10/10)

          Comment


            #6
            Originally posted by just_m3. View Post
            I thot you were writing this ) ! anyway .. the one who wrote it , ... took him an age and a half to do that ! (hope not) {}{}{}
            No bro not me there is the Zend link at the end of post, and this is just until Part 6 which i meant is ok for getting a clue about php basics, it goes to Part 15.

            Originally posted by icedroplet1987 View Post
            its awesome for everybody who is in mood to learn php but they do not have a clue about it. must be thanked by all members of forum as can see it took your time to make this post (10/10)
            Thanks. If i remember correctly, about an hour and half, but i think it was worth it. ;)
            Last edited by arnage; 03.04.12, 20:11.
            <!DOCTYPE html PUBLIC "-//WAPFORUM.RS

            Comment


              #7
              Originally posted by arnage View Post
              No bro not me there is the Zend link at the end of post, and this is just until Part 6 which i meant is ok for getting a clue about basics, it goes to Part 15.
              i know that ain't you ! : ))) you are still replying here ... i also "got" that link :p nice article .. and no problemo ;) ... !
              This is ten percent luck, twenty percent skill
              Fifteen percent concentrated power of will
              Five percent pleasure, fifty percent pain

              And a hundred percent reason to remember the name!

              Comment


                #8
                The best tutorial i ever found..... its better and cear than w3schools for me...thanks dude

                Comment


                  #9
                  You're welcome.
                  <!DOCTYPE html PUBLIC "-//WAPFORUM.RS

                  Comment

                  Working...
                  X