Learn Php In 10 Minutes

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Learn Php In 10 Minutes

    PLEASE DONT POST YOUR MESSAGES HERE...

    Learn PHP in 10 minutes its called like that..
    I rewrited this for this forum from book,took me hours..
    It is shorty all about php....enjoy


    Lesson 1
    Getting to Know PHP


    PHP Basics
    There is a good chance you already know a bit about what PHP can dothat is probably why you have picked up this book. PHP is hugely popular, and rightly so. Even if you haven't come across an existing user singing its praises, you've almost certainly used a website that runs on PHP. This lesson clarifies what PHP does, how it works, and what it is capable of.
    PHP is a programming language that was designed for creating dynamic websites. It slots into your web server and processes instructions contained in a web page before that page is sent through to your web browser. Certain elements of the page can therefore be generated on-the-fly so that the page changes each time it is loaded. For instance, you can use PHP to show the current date and time at the top of each page in your site, as you'll see later in this lesson.The name PHP is a recursive acronym that stands for PHP: Hypertext Preprocessor. It began life called PHP/FI, the "FI" part standing for Forms Interpreter. Though the name was shortened a while back, one of PHP's most powerful features is how easy it becomes to process data submitted in HTML forms. PHP can also talk to various database systems, giving you the ability to generate a web page based on a SQL query.For example, you could enter a search keyword into a form field on a web page, query a database with this value, and produce a page of matching results. You will have seen this kind of application many times before, at virtually any online store as well as many websites that do not sell anything, such as search engines.The PHP language is flexible and fairly forgiving, making it easy to learn even if you have not done any programming in the past. If you already know another language, you will almost certainly find similarities here. PHP looks like a cross between C, Perl, and Java, and if you are familiar with any of these, you will find that you can adapt your existing programming style to PHP with little effort.


    Server-Side Scripting
    The most important concept to learn when starting out with PHP is where exactly it fits into the grand scheme of things in a web environment. When you understand this, you will understand what PHP can and cannot do.
    The PHP module attaches to your web server, telling it that files with a particular extension should be examined for PHP code. Any PHP code found in the page is executedwith any PHP code replaced by the output it producesbefore the web page is sent to the browser.File Extensions The usual web server configuration is that somefile.php will be interpreted by PHP, whereas somefile.html will be passed straight through to the web browser, without PHP getting involved.The only time the PHP interpreter is called upon to do something is when a web page is loaded. This could be when you click a link, submit a form, or just type in the URL of a web page. When the web browser has finished downloading the page, PHP plays no further part until your browser requests another page.Because it is only possible to check the values entered in an HTML form when the submit button is clicked, PHP cannot be used to perform client-side validationin other words, to check that the value entered in one field meets certain criteria before allowing you to proceed to the next field. Client-side validation can be done using JavaScript, a language that runs inside the web browser itself, and JavaScript and PHP can be used together if that is the effect you require.The beauty of PHP is that it does not rely on the web browser at all; your script will run the same way whatever browser you use. When writing server-side code, you do not need to worry about JavaScript being enabled or about compatibility with older browsers beyond the ability to display HTML that your script generates or is embedded in.

    PHP Tags
    Consider the following extract from a PHP-driven web page that displays the current date:

    Code:
    Today is <?php echo date(&#39;j F Y&#39;);?>
    The <?php tag tells PHP that everything that follows is program code rather than HTML, until the closing ?> tag. In this example, the echo command tells PHP to display the next item to screen; the following date command produces a formatted version of the current date, containing the day, month, and year.The Statement Terminator The semicolon character is used to indicate the end of a PHP command. In the previous examples, there is only one command, and the semicolon is not actually required, but it is good practice to always include it to show that a command is complete.
    In this book PHP code appears inside tags that look like <?php ... ?>. Other tag styles can be used, so you may come across other people&#39;s PHP code beginning with tags that look like <? (the short tag), <% (the ASP tag style) or <script LANGUAGE="php"> (the script tag).Of the different tag styles that can be used, only the full <?php tag and the script tag are always available. The others are turned off or on by using a PHP configuration setting. We will look at the php.ini configuration file in Lesson 23, "PHP Configuration."
    Standard PHP Tags It is good practice to always use the <?php tag style so your code will run on any system that has PHP installed, with no additional configuration needed. If you are tempted to use <? as a shortcut, know that any time you move your code to another web server, you need to be sure it will understand this tag style. Anything that is not enclosed in PHP tags is passed straight through to the browser, exactly as it appears in the script. Therefore, in the previous example, the text Today is appears before the generated date when the page is displayed.

    #2
    Your First Script
    Before you go any further, you need to make sure you can create and run PHP scripts as you go through the examples in this book. This could be on your own machine, and you can find instructions for installing PHP in Appendix A, "Installing PHP." Also, many web hosting companies include PHP in their packages, and you may already have access to a suitable piece of web space.
    Go ahead and create a new file called time.php that contains Listing 1.1, in a location that can be accessed by a PHP-enabled web server. This is a slight variation on the date example shown previously.
    Listing 1.1. Displaying the System Date and Time
    Code:
    The time is
    <?php echo date(&#39;H:i:s&#39;);?>
    and the date is
    <?php echo date(&#39;j F Y&#39;);?>
    When you enter the URL to this file in your web browser, you should see the current date and time, according to the system clock on your web server, displayed.
    Running PHP Locally If you are running PHP from your local PC, PHP code in a script will be executed only if it is accessed through a web server that has the PHP module enabled. If you open a local script directly in the web browserfor instance, by double-clicking or dragging and dropping the file into the browserit will be treated as HTML only.
    Web Document Location If you were using a default Apache installation in Windows, you would create time.php in the folder C:\Program Files\Apache Group\Apache\htdocs, and the correct URL would be http://localhost/time.php.
    If you entered Listing 1.1 exactly as shown, you might notice that the actual output produced could be formatted a little betterthere is no space between the time and the word and. Any line in a script that only contains code inside PHP tags will not take up a line of output in the generated HTML.
    If you use the View Source option in your web browser, you can see the exact output produced by your script, which should look similar to the following:
    The time is
    15:33:09and the date is
    13 October 2004
    If you insert a space character after ?>, that line now contains non-PHP elements, and the output is spaced correctly.

    The echo Command
    While PHP is great for embedding small, dynamic elements inside a web page, in fact the whole page could consist of a set of PHP instructions to generate the output if the entire script were enclosed in PHP tags.

    The echo commandis used to send output to the browser. Listing 1.1 uses echo to display the result of the date command, which returns a string that contains a formatted version of the current date. Listing 1.2 does the same thing but uses a series of echo commands in a single block of PHP code to display the date and time.

    Listing 1.2. Using echo to Send Output to the Browser
    Code:
    <?php
    echo "The time is ";
    echo date(&#39;H:i:s&#39;);
    echo " and the date is ";
    echo date(&#39;j F Y&#39;);
    ?>
    The non-dynamic text elements you want to output are contained in quotation marks. Either double quotes (as used in Listing 1.2) or single quotes (the same character used for an apostrophe) can be used to enclose text strings, although you will see an important difference between the two styles in Lesson 2, "Variables." The following statements are equally valid:

    Code:
    echo "The time is ";
    echo &#39;The time is &#39;;
    Notice that space characters are used in these statements inside the quotation marks to ensure that the output from date is spaced away from the surrounding text. In fact the output from Listing 1.2 is slightly different from that for Listing 1.1, but in a web browser you will need to use View Source to see the difference. The raw output from Listing 1.2 is as follows:

    The time is 15:59:50 and the date is 13 October 2004

    There are no line breaks in the page source produced this time. In a web browser, the output looks just the same as for Listing 1.1 because in HTML all whitespace, including carriage returns and multiple space or tab characters, is displayed as a single space in a rendered web page.
    A newline character inside a PHP code block does not form part of the output. Line breaks can be used to format the code in a readable way, but several short commands could appear on the same line of code, or a long command could span several linesthat&#39;s why you use the semicolon to indicate the end of a command.
    Listing 1.3 is identical to Listing 1.2 except that the formatting makes this script almost unreadable.

    Comment


      #3
      Listing 1.3. A Badly Formatted Script That Displays the Date and Time
      Code:
      <?php echo "The time is ";  echo date(&#39;H:i:s&#39;); echo
      " and the date is "
      ; echo date(
      &#39;j F Y&#39;
      );
      ?>
      Using Newlines If you wanted to send an explicit newline character to the web browser, you could use the character sequence \n. There are several character sequences like this that have special meanings, and you will see more of them in Lesson 6, "Working with Strings."

      Comments
      Another way to make sure your code remains readable is by adding comments to it. A comment is a piece of free text that can appear anywhere in a script and is completely ignored by PHP. The different comment styles supported by PHP are shown in Table 1.1.

      Table 1.1. Comment Styles in PHP Comment
      Description

      // or #
      Single-line comment. Everything to the end of the current line is ignored.

      /* ... */
      Single- or multiple-line comment. Everything between /* and */ is ignored.

      Listing 1.4 produces the same formatted date and time as Listings 1.1, 1.2, and 1.3, but it contains an abundance of comments. Because the comments are just ignored by PHP, the output produced consists of only the date and time.

      Listing 1.4. Using Comments in a Script
      Code:
      <?php
      /* time.php
         This script prints the current date
         and time in the web browser
      */
      
      echo "The time is ";
      echo date(&#39;H:i:s&#39;);  // Hours, minutes, seconds
      
      echo " and the date is ";
      echo date(&#39;j F Y&#39;);  // Day name, month name, year
      ?>
      Listing 1.4 includes a header comment block that contains the filename and a brief description, as well as inline comments that show what each date command will produce



      Lesson 2
      Variables


      Understanding Variables
      Variablescontainers in which values can be stored and later retrievedare a fundamental building block of any programming language.

      For instance, you could have a variable called number that holds the value 5 or a variable called name that holds the value Chris. The following PHP code declares variables with those names and values:

      Code:
      $number = 5;
      $name = "Chris";
      In PHP, a variable name is always prefixed with a dollar sign. If you remember that, declaring a new variable is very easy: You just use an equals symbol with the variable name on the left and the value you want it to take on the right.

      Declaring Variables
      Unlike in some programming languages, in PHP variables do not need to be declared before they can be used. You can assign a value to a new variable name any time you want to start using it.

      Variables can be used in place of fixed values throughout the PHP language. The following example uses echo to display the value stored in a variable in the same way that you would display a piece of fixed text:

      Code:
      $name = "Chris";
      echo "Hello, ";
      echo $name;
      The output produced is
      Hello, Chris

      Naming Variables
      The more descriptive your variable names are, the more easily you will remember what they are used for when you come back to a script several months after you write it.

      It is not usually a good idea to call your variables $a, $b, and so on. You probably won&#39;t remember what each letter stood for, if anything, for long. Good variable names tell exactly what kind of value you can expect to find stored in them (for example, $price or $name).

      Case-Sensitivity Variable names in PHP are case-sensitive. For example, $name is a different variable than $Name, and the two could store different values in the same script.

      Variable names can contain only letters, numbers, and the underscore character, and each must begin with a letter or underscore. Table 2.1 shows some examples of valid and invalid variable names.

      Table 2.1. Examples of Valid and Invalid Variable Names
      Valid Variable Names......... Invalid Variable Names

      $percent ......... $pct%

      $first_name ......... first-name

      $line_2 ......... $2nd_line

      Using Underscores
      Using the underscore character is a handy way to give a variable a name that is made up of two or more words. For example $first_name and $date_of_birth are more readable for having underscores in place.

      Another popular convention for combining words is to capitalize the first letter of each wordfor example, $FirstName and $DateOfBirth. If you prefer this style, feel free to use it in your scripts but remember that the capitalization does matter.


      Expressions
      When a variable assignment takes place, the value given does not have to be a fixed value. It could be an expressiontwo or more values combined using an operator to produce a result. It should be fairly obvious how the following example works, but the following text breaks it down into its components:

      Code:
      $sum = 16 + 30;
      echo $sum;
      The variable $sum takes the value of the expression to the right of the equals sign. The values 16 and 30 are combined using the addition operatorthe plus symbol (+)and the result of adding the two values together is returned. As expected, this piece of code displays the value 46.

      To show that variables can be used in place of fixed values, you can perform the same addition operation on two variables:

      Code:
      $a = 16;
      $b = 30;
      $sum = $a + $b;
      echo $sum;
      The values of $a and $b are added together, and once again, the output produced is 46.

      Comment


        #4
        Variables in Strings
        You have already seen that text strings need to be enclosed in quotation marks and learned that there is a difference between single and double quotes.

        The difference is that a dollar sign in a double-quoted string indicates that the current value of that variable should become part of the string. In a single-quoted string, on the other hand, the dollar sign is treated as a literal character, and no reference is made to any variables.

        The following examples should help explain this. In the following example, the value of variable $name is included in the string:

        Code:
        $name = "Chris";
        echo "Hello, $name";
        This code displays Hello, Chris.

        In the following example, this time the dollar sign is treated as a literal, and no variable substitution takes place:

        Code:
        $name = &#39;Chris&#39;;
        echo &#39;Hello, $name&#39;;
        This code displays Hello, $name.

        Sometimes you need to indicate to PHP exactly where a variable starts and ends. You do this by using curly brackets, or braces ({}). If you wanted to display a weight value with a suffix to indicate pounds or ounces, the statement might look like this:

        Code:
        echo "The total weight is {$weight}lb";
        If you did not use the braces around $weight, PHP would try to find the value of $weightlb, which probably does not exist in your script.

        You could do the same thing by using the concatenation operator, the period symbol, which can be used to join two or more strings together, as shown in the following example:

        Code:
        echo &#39;The total weight is &#39; . $weight . &#39;lb&#39;;
        The three values two fixed strings and the variable $weightare simply stuck together in the order in which they appear in the statement. Notice that a space is included at the end of the first string because you want the value of $weight to be joined to the word is.

        If $weight has a value of 99, this statement will produce the following output:

        The total weight is 99lb

        Data Types
        Every variable that holds a value also has a data type that defines what kind of value it is holding. The basic data types in PHP are shown in Table 2.2.

        Table 2.2. PHP Data Types
        Data Type..........Description

        Boolean..........A truth value; can be either TRUE or FALSE.

        Integer..........A number value; can be a positive or negative whole number.

        Double (or float)..........A floating-point number value; can be any decimal number.

        String..........An alphanumeric value; can contain any number of ASCII characters.

        When you assign a value to a variable, the data type of the variable is also set. PHP determines the data type automatically, based on the value you assign. If you want to check what data type PHP thinks a value is, you can use the gettype function.

        Running the following code shows that the data type of a decimal number is double:

        Code:
        $value = 7.2;
        echo gettype($value);
        The complementary function to gettype is settype, which allows you to override the data type of a variable. If the stored value is not suitable to be stored in the new type, it will be modified to the closest value possible.

        The following code attempts to convert a string value into an integer:

        Code:
        $value =  "22nd January 2005";
        settype($value, "integer");
        echo $value
        ;

        In this case, the string begins with numbers, but the whole string is not an integer. The conversion converts everything up to the first nonnumeric character and discards the rest, so the output produced is just the number 22.

        Analyzing Data Types In practice, you will not use settype and gettype very often because you will rarely need to alter the data type of a variable. This book covers this topic early on so that you are aware that PHP does assign a data type to every variable.

        Comment


          #5
          Type Juggling
          Sometimes PHP will perform an implicit data type conversion if values are expected to be of a particular type. This is known as type juggling.

          For example, the addition operator expects to sit between two numbers. String type values are converted to double or integer before the operation is performed, so the following addition produces an integer result:

          Code:
          echo 100 + "10 inches";
          This expression adds 100 and 10, and it displays the result 110.

          A similar thing happens when a string operator is used on numeric data. If you perform a string operation on a numeric type, the numeric value is converted to a string first. In fact, you already saw this earlier in this lesson, with the concatenation operatorthe value of $weight that was displayed was numeric.

          The result of a string operation will always be a string data type, even if it looks like a number. The following example produces the result 69, butas gettype shows$number contains a string value:

          Code:
          $number = 6 . 9;
          echo $number;
          echo gettype(6 . 9);
          We will look at the powerful range of operators that are related to numeric and string data types in PHP in Lessons 5, "Working with Numbers," and 6, "Working with Strings."

          Variable Variables
          It is possible to use the value stored in a variable as the name of another variable. If this sounds confusing, the following example might help:

          Code:
          $my_age = 21;
          $varname = "my_age";
          echo "The value of $varname is ${$varname}";
          The output produced is
          The value of my_age is 21

          Because this string is enclosed in double quotes, a dollar sign indicates that a variable&#39;s value should become part of the string. The construct ${$varname} indicates that the value of the variable named in $varname should become part of the string and is known as a variable variable.

          The braces around $varname are used to indicate that it should be referenced first; they are required in double-quoted strings but are otherwise optional. The following example produces the same output as the preceding example, using the concatenation operator:

          Code:
          echo &#39;The value of &#39; . $varname . &#39; is &#39; . $$varname;

          Comment


            #6
            Lesson 3
            Flow Control


            Conditional Statements
            A conditional statement in PHP begins with the keyword if, followed by a condition in parentheses. The following example checks whether the value of the variable $number is less than 10, and the echo statement displays its message only if this is the case:

            Code:
            $number = 5;
            if ($number < 10) {
              echo "$number is less than ten";
            }
            The condition $number < 10 is satisfied if the value on the left of the < symbol is smaller than the value on the right. If this condition holds true, then the code in the following set of braces will be executed; otherwise, the script jumps to the next statement after the closing brace.

            Boolean Values Every
            conditional expression evaluates to a Boolean value, and an if statement simply acts on a trUE or FALSE value to determine whether the next block of code should be executed. Any zero value in PHP is considered FALSE, and any nonzero value is considered trUE.
            As it stands, the previous example will be trUE because 5 is less than 10, so the statement in braces is executed, and the corresponding output is displayed. Now, if you change the initial value of $number to 10 or higher and rerun the script, the condition fails, and no output is produced.
            Braces are used in PHP to group blocks of code together. In a conditional statement, they surround the section of code that is to be executed if the preceding condition is true.

            Brackets and Braces
            You will come across three types of brackets when writing PHP scripts. The most commonly used terminology for each type is parentheses (()), braces ({}), and square brackets ([]).
            Braces are not required after an if statement. If they are omitted, the following single statement is executed if the condition is true. Any subsequent statements are executed, regardless of the status of the conditional.

            Braces and Indentation
            Although how your code is indented makes no difference to PHP, it is customary to indent blocks of code inside braces with a few space characters to visually separate that block from other statements.
            Even if you only want a condition or loop to apply to one statement, it is still useful to use braces for clarity. It is particularly important in order to keep things readable when you&#39;re nesting multiple constructs.

            Conditional Operators
            PHP allows you to perform a number of different comparisons, to check for the equality or relative size of two values. PHP&#39;s conditional operators are shown in Table 3.1.

            Table 3.1. Conditional Operators in PHP
            Operator........... Description

            ==...........Is equal to

            ===...........Is identical to (is equal and is the same data type)

            !=...........Is not equal to

            !==........... Is not identical to

            <...........Is less than

            <=...........Is less than or equal to

            >...........Is greater than

            >=...........Is greater than or equal to

            = or ==? Be careful when comparing for equality to use a double equals symbol (==). A single = is always an assignment operator and, unless the value assigned is zero, your condition will always return trueand remember that TRUE is any nonzero value. Always use == when comparing two values to avoid headaches.

            Comment


              #7
              Logical Operators
              You can combine multiple expressions to check two or more criteria in a single conditional statement. For example, the following statement checks whether the value of $number is between 5 and 10:

              Code:
              $number = 8;
              if ($number >= 5 and $number <= 10) {
                echo "$number is between five and ten";
              }
              The keyword and is a logical operator, which signifies that the overall condition will be true only if the expressions on either side are true. That is, $number has to be both greater than or equal to 5 and less than or equal to 10.

              Table 3.2 shows the logical operators that can be used in PHP.

              Table 3.2. Logical Operators in PHP
              Operator.........Name.........Description

              ! a.........NOT.........True if a is not true

              a && b.........AND.........True if both a and b are true

              a || b.........OR.........True if either a or b is true

              a and b.........AND.........True if both a and b are true

              a xor b.........XOR.........True if a or b is true, but not both

              a or b.........OR......... True if either a or b is true

              You may have noticed that there are two different ways of performing a logical AND or OR in PHP. The difference between and and && (and between or and ||) is the precedence used to evaluate expressions.

              Table 3.2 lists the highest-precedence operators first. The following conditions, which appear to do the same thing, are subtly but significantly different:

              a or b and c
              a || b and c

              In the former condition, the and takes precedence and is evaluated first. The overall condition is true if a is true or if both b and c are true.

              In the latter condition, the || takes precedence, so c must be true, as must either a or b, to satisfy the condition.

              Operator Symbols
              Note that the logical AND and OR operators are the double symbols && and ||, respectively. These symbols, when used singularly, have a different meaning, as you will see in Lesson 5, "Working with Numbers."


              Multiple Condition Branches
              By using an else clause with an if statement, you can specify an alternate action to be taken if the condition is not met. The following example tests the value of $number and displays a message that says whether it is greater than or less than 10:

              Code:
              $number = 16;
              if ($number < 10) {
                echo "$number is less than ten";
              }
              else {
                echo "$number is more than ten";
              }
              The else clause provides an either/or mechanism for conditional statements. To add more branches to a conditional statement, the elseif keyword can be used to add a further condition that is checked only if the previous condition in the statement fails.

              The following example uses the date function to find the current time of daydate("H") gives a number between 0 and 23 that represents the hour on the clockand displays an appropriate greeting:

              Code:
              $hour = date("H");
              if ($hour < 12) {
                echo "Good morning";
              }
              elseif ($hour < 17) {
                echo "Good afternoon";
              }
              else {
                echo "Good evening";
              }
              This code displays Good morning if the server time is between midnight and 11:59, Good afternoon from midday to 4:59 p.m., and Good evening from 5 p.m. onward.

              Notice that the elseif condition only checks that $hour is less than 17 (5 p.m.). It does not need to check that the value is between 12 and 17 because the initial if condition ensures that PHP will not get as far as the elseif if $hour is less than 12.

              The code in the else clause is executed if all else fails. For values of $hour that are 17 or higher, neither the if nor the elseif condition will be true.

              elseif Versus else if In PHP you can also write elseif as two words: else if. The way PHP interprets this variation is slightly different, but its behavior is exactly the same.

              The switch Statement
              An if statement can contain as many elseif clauses as you need, but including many of these clauses can often create cumbersome code, and an alternative is available. switch is a conditional statement that can have multiple branches in a much more compact format.

              The following example uses a switch statement to check $name against two lists to see whether it belongs to a friend:

              Code:
              switch ($name) {
                case "Damon":
                case "Shelley":
                  echo "Welcome, $name, you are my friend";
                  break;
                case "Adolf":
                case "Saddam":
                  echo "You are no friend of mine, $name";
                  break;
                default:
                  echo "I do not know who you are, $name";
              }
              Each case statement defines a value for which the next block of PHP code will be executed. If you assign your first name to $name and run this script, you will be greeted as a friend if your name is Damon or Shelley, and you will be told that you are not a friend if your name is either Adolf or Saddam. If you have any other name, the script will tell you it does not know who you are.

              There can be any number of case statements preceding the PHP code to which they relate. If the value that is being tested by the switch statement (in this case $name) matches any one of them, any subsequent PHP code will be executed until a break command is reached.

              Breaking Out
              The break statement is important in a switch statement. When a case statement has been matched, any PHP code that follows will be executedeven if there is another case statement checking for a different value. This behavior can sometimes be useful, but mostly it is not what you wantso remember to put a break after every case.

              Any other value for $name will cause the default code block to be executed. As with an else clause, default is optional and supplies an action to be taken if nothing else is appropriate

              Loops
              PHP offers three types of loop constructs that all do the same thingrepeat a section of code a number of timesin slightly different ways.

              The while Loop
              The while keyword takes a condition in parentheses, and the code block that follows is repeated while that condition is true. If the condition is false initially, the code block will not be repeated at all.

              Infinite Loops The repeating code must perform some action that affects the condition in such a way that the loop condition will eventually no longer be met; otherwise, the loop will repeat forever.

              The following example uses a while loop to display the square numbers from 1 to 10:

              Code:
              $count = 1;
              while ($count <= 10) {
                $square = $count * $count;
                echo "$count squared is $square 
              ";
                $count++;
              }
              The counter variable $count is initialized with a value of 1. The while loop calculates the square of that number and displays it, then adds one to the value of $count. The ++ operator adds one to the value of the variable that precedes it.
              The loop repeats while the condition $count <= 10 is true, so the first 10 numbers and their squares are displayed in turn, and then the loop ends.

              The do Loop
              The do loop is very similar to the while loop except that the condition comes after the block of repeating code. Because of this variation, the loop code is always executed at least onceeven if the condition is initially false.
              The following do loop is equivalent to the previous example, displaying the numbers from 1 to 10, with their squares:

              Code:
              $count = 1;
              do {
                $square = $count * $count;
                echo "$count squared is $square 
              ";
                $count++;
              } while ($count <= 10);
              The for Loop
              The for loop provides a compact way to create a loop. The following example performs the same loop as the previous two examples:

              Code:
              for ($count = 1; $count <= 10; $count++) {
                $square = $count * $count;
                echo "$count squared is $square 
              ";
              }
              As you can see, using for allows you to use much less code to do the same thing as with while and do.
              A for statement has three parts, separated by semicolons:
              The first part is an expression that is evaluated once when the loop begins. In the preceding example, you initialized the value of $count.
              The second part is the condition. While the condition is true, the loop continues repeating. As with a while loop, if the condition is false to start with, the following code block is not executed at all.
              The third part is an expression that is evaluated once at the end of each pass of the loop. In the previous example, $count is incremented after each line of the output is displayed.

              Nesting Conditions and Loops
              So far you have only seen simple examples of conditions and loops. However, you can nest these constructs within each other to create some quite complex rules to control the flow of a script.

              Remember to Indent
              The more complex the flow control in your script is, the more important it becomes to indent your code to make it clear which blocks of code correspond to which constructs.

              Breaking Out of a Loop
              You have already learned about using the keyword break in a switch statement. You can also use break in a loop construct to tell PHP to immediately exit the loop and continue with the rest of the script.
              The continue keyword is used to end the current pass of a loop. However, unlike with break, the script jumps back to the top of the same loop and continues execution until the loop condition fails.



              Lesson 4
              Functions


              Using Functions
              A function is used to make a task that might consist of many lines of code into a routine that can be called using a single instruction.
              PHP contains many functions that perform a wide range of useful tasks. Some are built in to the PHP language; others are more specialized and are available only if certain extensions are activated when PHP is installed.
              The online PHP manual (http://www.php.net) is an invaluable reference. As well as documentation for every function in the language, the manual pages are also annotated with user-submitted tips and examples, and you can even submit your own comments if you want.
              Online Reference To quickly pull up the PHP manual page for any function, use this shortcut: http://www.php.net/function_name
              You have already used the date function to generate a string that contains a formatted version of the current date. Let&#39;s take a closer look at how that example from Lesson 1, "Getting to Know PHP," works. The example looked like this:

              Code:
              echo date(&#39;j F Y&#39;);
              The online PHP manual gives the prototype for date as follows:

              string date (string format [, int timestamp])

              This means that date takes a string argument called format and, optionally, the integer timestamp. It returns a string value. This example sends j F Y to the function as the format argument, but timestamp is omitted. The echo command displays the string that is returned.

              Prototypes
              Every function has a prototype that defines how many arguments it takes, the arguments&#39; data types, and what value is returned. Optional arguments are shown in square brackets ([]).

              Defining Functions
              In addition to the built-in functions, PHP allows you to define your own. There are advantages to using your own function. Not only do you have to type less when the same piece of code has to be executed several times but a custom-defined function also makes your script easier to maintain. If you want to change the way a task is performed, you only need to update the program code oncein the function definitionrather than fix it every place it appears in your script.

              Modular Code
              Grouping tasks into functions is the first step toward modularizing your codesomething that is especially important to keep your scripts manageable as they grow in size and become more complex.
              The following is a simple example that shows how a function is defined and used in PHP:

              Code:
              function add_tax($amount) {
                $total = $amount * 1.09;
                return $total;
              }
              
              $price = 16.00;
              echo "Price before tax: $price 
              ";
              echo "Price after tax: ";
              echo add_tax($price);
              The function keyword defines a function called add_tax that will execute the code block that follows. The code that makes up a function is always contained in braces. Putting $amount in parentheses after the function name stipulates that add_tax takes a single argument that will be stored in a variable called $amount inside the function.
              The first line of the function code is a simple calculation that multiplies $amount by 1.09which is equivalent to adding 9% to that valueand assigns the result to $total. The return keyword is followed by the value that is to be returned when the function is called from within the script.

              Running this example produces the following output:

              Price before tax: 16
              Price after tax: 17.44

              This is an example of a function that you might use in many places in a web page; for instance, on a page that lists all the products available in an online store, you would call this function once for each item that is displayed to show the after-tax price. If the rate of tax changes, you only need to change the formula in add_tax to alter every price displayed on that page.

              Comment

              Working...
              X