Top Banner
PHP Building Blocks Yasar Hussain Malik - NISTE
22

PHP Building Blocks

Feb 11, 2016

Download

Documents

Mohawk

PHP Building Blocks. Yasar Hussain Malik - NISTE. PHP Building Blocks. Code blocks - chunks of PHP code that are separate from the rest of the script. PHP uses braces, { and }, to open and close code blocks - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: PHP Building Blocks

PHP Building Blocks

Yasar Hussain Malik - NISTE

Page 2: PHP Building Blocks

Code blocks - chunks of PHP code that are separate from the rest of the script.

PHP uses braces, { and }, to open and close code blocks

<?="Hello, world!" ?> Here is the equivalent written using the

standard open and closing tags: <?php

    print "Hello, world!";?>

PHP Building Blocks

Page 3: PHP Building Blocks

PHP has three ways of inserting comments: //, /* */, and #. // and # mean, "ignore the rest of this line” whereas /* means "ignore everything until you see */". <?php

    print "This is printed\n";    // print "This is not printed\n";    # print "This is not printed\n";    print "This is printed\n";    /* print "This is not printed\n";    print "This is not printed\n"; */?>

Above code shows all three types of comments in action, but does not demonstrate the problem with the /* */ form of commenting.

Comments

Page 4: PHP Building Blocks

The if Statement Here it shows that how a group of statements can be executed based on a

condition. Like in human language. For example, somebody can say, if a condition is true, do that and that and that. In PHP “if” is a reserved word. The “if” must be in lowercase. This is used to check if a condition is true. If it is

true, one or more statements are executed. Let us     <?php

        $Var = 20;

        if ($Var == 20)            {                echo "I am studying PHP";            }

    ?>

Conditional statements

Page 5: PHP Building Blocks

The first statement assigns the value 20 to the variable, $Var. The if-statement begins with the reserved word, “if” and ends with the

curly brace, }. What goes inside the parentheses is the condition. The statements to be executed are in the curly braces. If there is only one statement, you do not need the curly braces. If you

have more than one statement, separate them with semicolons and put them within the curly braces, {}.

If the condition is correct, PHP will execute it In the above code, 20 was assigned to, $Var. So, $Var equals 20. In the

condition the equal sign is two assignment operators: The if-statement above can be read like this:

if $Var equals 20 then display, 'I am studying PHP'. Since we assigned the value 20 to $Var, the condition of the if-statement is true. So the statement in the curly braces is executed.

Page 6: PHP Building Blocks

ElseIn the above code, the statement(s) in the curly braces is(are) executed if the condition is true.

What about, if it were false? It would be false if we never assigned 20 to $Var. If it were false, nothing will happen. That is, the

statement(s) in the curly braces will not be executed. The else part is similar in coding to the if part. However, its block (curly braces) is executed when

the if’s condition is false. The else part does not have any condition. Try the following code:

    <?php

        $Var = 36;

        if ($Var == 20)            {                echo 'I am studying PHP';            }        else            {                echo 'I am doing something else';            }

    ?>

Also note that else is a reserved word.

Page 7: PHP Building Blocks

elseifYou may have more than one test to make in a particular situation or for the same variable. In this case you include the “elseif” reserved word as in the following code. Try it.

    <?php     $Var = 1000;

    if ($Var == 10)         {             echo 'Value is small'; }

    elseif ($Var == 100)         {             echo 'Value is medium‘;     }

    elseif ($Var == 1000)         {             echo 'Value is large';  }

    ?> A value of 1000 is assigned to Var. The if-elseif coding will test if $Var is 10; if it is the

corresponding block will display 'Value is small'. The code will then test if $Var is 100; if it is (which it is not), the corresponding block will

display, 'Value is medium'. The code will then test if $Var is 1000; if it is, the corresponding block will display, 'Value is

large'. With the if-elseif coding only one of the blocks can be executed; that is, only one of the conditions can be true (the rest should be false).

Always remember this: the if-elseif coding is used only for situations where only one of the conditions is satisfied (is true).

Page 8: PHP Building Blocks

Default ConditionWhat about the situation for an if-elseif coding where none of the conditions is true? This is an opportunity to give some default answer. You do this by simply adding the else (no condition) section at the end of the if-elseif coding. The following code illustrates this:

    <?php

    $Var = 10000;

    if ($Var == 10)        {            echo 'Value is small';        }    elseif ($Var == 100)        {            echo 'Value is medium';        }    elseif ($Var == 1000)        {            echo 'Value is large';        }    else        {            echo '$Var is very large';        }

    ?>

Page 9: PHP Building Blocks

Complete Syntax for if-StatementThe complete syntax for the if-statement is:

if (condition)    {        statements    }elseif (condition)    {        statements    }elseif (condition)    {        statements    }

            -  -  -

else    {        statements    }

Note: if the “if” or “elseif” or “else” part has just one statement, then you do not need curly braces for the statement. You need curly braces if there is more than one statement.

Page 10: PHP Building Blocks

    <?php         $hisVar = 10000;

        switch ($hisVar)            {                case 10:                echo 'Value is small';                break;                case 100:                echo 'Value is medium';                break;                case 1000:                echo 'Value is large';                break;                default:                echo '$hisVar is very large';         }

    ?>The syntax for the switch statement is:switch (expression)    {       case label :            statements;            break;       case label :            statements;            break;       -  -  -       default :            statements;    }

With time you will know different possible expressions. An example is just a variable, as in the above case. label is the result of the expression. Each case ends with “break;”. The last situation does not have a label (corresponds to else).

The switch Statement

Page 11: PHP Building Blocks

PHP loops are control structures and you can use them execute a code block more times. It means you don't have to copy and paste your code many times in the file just use a right loop statement.

echo " 1 "; echo " 2 "; echo " 3 "; echo " 4 "; echo " 5 "; echo " 6 "; echo " 7 "; echo " 8 "; cho " 9 ";

And with a for loop it looks like this: for ($i=1;$i<=9;$i++){ echo " $i ";} And the output of both code is similar:

Output: 1 2 3 4 5 6 7 8 9

Loops

Page 12: PHP Building Blocks

The solution with loop is much better. It is shorter more easy to understand.

Besides this in most cases you don't know during the coding how many times the code block needs to be executed.After this short example let's see what kind of loop statements are in PHP.

1. while loop 2. do ... while loop 3. for loop 4. foreach loop Besides this you can control your loops with:5. break 6. continue

…Loops

Page 13: PHP Building Blocks

Maybe this is the simplest loop in PHP. The syntax is quite easy:

while (condition) code block

The code block will be executed until the condition is true. It means that it can happen that it will never executed. To implement our first example with while loop looks like this:

$i=1; while ($i<=9){ echo " $i "; $i++; } The output will be exactly the same as before. However if you

initialise $i variable with 10 ($i=10) then nothing will be displayed. If you forgot to increment the variable it will result an endless loop as

the condition will be never changed and it is always true.

The PHP while loop

Page 14: PHP Building Blocks

This loop variant is very similar to the while loop. However there is one important difference. With do while loop the code block will be executed at least once. This is because in case of a do while loop PHP checks the condition only after the first iteration. It is clearly visible from the syntax:

do { code block } while (condition)

Besides this there is no more difference to the basic while loop. Here is the example how to use it:

$i=1; do { echo " $i "; $i++; } while ($i<=9)

The do while loop

Page 15: PHP Building Blocks

In for loops ◦ make the loop variable initialization◦ conditional check◦ loop variable update in a single line. The syntax is the following:

for ( expression1; condition; expression2 ) code blockThe expression1 contains the initialization part of the loop. You can set the loop variable like $i=1. You can write your condition here and it will be checked before each iterationThe expression2 code is relevant to update the loop variable.A real example looks like this:

for($i=1;$i<=9;$i++){

echo " $i ";}

Each element of the header can be empty or contain multiple expressions separated by commas. With this you can make the above code even smaller. However it can be more difficult to maintain the code:

for( $i=1, $a=0; $i<=9; print " $i ", $i++);

The for loop

Page 16: PHP Building Blocks

This is a special loop as you can use it only for arrays. The goal of the foreach loop to iterate over each element of an array. If you try to use it with a normal variable you will get an error. The syntax is:foreach (array as $value) code block

It means that in each iteration the actual array value will be copied to the $value variable and you can use it in the code block. So the code to provide our usual output is:

$myList = array(1,2,3,4,5,6,7,8,9); foreach ($myList as $value) { echo " $value "; } There is an alternative syntax of the foreach loop to handle associative arrays. You

can use this if you want to know not only the actual element value but the key as well. The syntax is:

foreach (array as $key => $value) code block

In this case you can use both information in your code block like this: $myList = array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5, 'f'=>6,'g'=>7,'h'=>8,'i'=>9); foreach ($myList as $key => $value) { echo " $key-$value “; }

The foreach loop

Page 17: PHP Building Blocks

Perhaps surprisingly, infinite loops can sometimes be helpful in your scripts. As infinite loops never terminate without outside influence, the most popular way to use them is to break out of the loop and/or exit the script entirely from within the loop whenever a condition is matched. You can also rely on user input to terminate the loop – ◦ if you are writing a program to accept people typing in data for as long as they want, it just would

not work to have the script loop 30,000 times or even 300,000,000 times. Instead, the code should loop forever, constantly accepting user input until the user ends the program by pressing Ctrl-C.

In PHP, you should clear of infinite loops as they can cause problems.

If you want to try them out, here are the most common examples of infinite loops: <?php

    while(1) {        print "In loop!\n";    }?>

As "1" also evaluates to true, that loop will continue on forever. Many people also like to write their infinite loops like this:

<?php    for (;;) {        print "In loop!\n";    }?>

In that example, the for loop is missing the declaration, condition, and action parts, meaning that it will always loop.

Infinite loops

Page 18: PHP Building Blocks

There are two special keywords you can use with loops, and they are "break" and "continue". it is used there to exit a block of loop. When used inside loops in order to manipulate the loop behaviour:

break causes PHP to exit the loop and carry on immediately after it continue causes PHP to skip the rest of the current loop iteration and go onto the next code. For example: <?php

    for ($i = 1; $i < 10; $i = $i + 1) {        if ($i == 3) continue;        if ($i == 7) break;        print "Number $i\n";    }?>

That is a modified version of our original for loop script. This time the output is this: Number 1

Number 2Number 4Number 5Number 6

Note that number 3 is missed out entirely, and the script exits after number 6. The reason for this is because of the two if statements - if the current number is 3, "continue" is used to skip the rest of that iteration and go on to number 4. Also, if the number is 7, "break" is used to exit the loop altogether.

Special loop keywords

Page 19: PHP Building Blocks

One of the most basic operations in PHP is including one script from another, thereby sharing functionality. This is done by using the include keyword, and specifying the filename you want to include.

For example, consider the following file, foo.php: <?php

    print 'Starting foo\n';    include 'bar.php';    print 'Finishing foo\n';?>

And also the file bar.php: <?php

    print 'In bar\n';?>

Including other files

Page 20: PHP Building Blocks

PHP would load the file bar.php, read in its contents, then put it into foo.php in place of the "include 'bar.php'" line. Therefore, foo.php would look like this:

<?php    print 'Starting foo\n';    print 'In bar\n';    print 'Finishing foo\n';?>

If you were wondering why it only writes in the "In bar" line and not the opening and closing tags, it's because whenever PHP includes another file, it drops out of PHP mode, then re-enters PHP mode as soon as it comes back from the file. Therefore, foo.php, once merged with bar.php, will actually look like this:

<?php    print 'Starting foo\n';?><?php    print 'In bar\n';?><?php    print 'Finishing foo\n';?>

It has the same effect, but it is a little harder to read! It is important to note that PHP only includes a file if the include line is actually executed.

Therefore, the following code would never include bar.php: <?php

    if (53 > 99) {        include 'bar.php';    }?>

…Including other files

Page 21: PHP Building Blocks

If you attempt to include a file that does not exist, PHP will generate a warning message. If you find that you write a script that absolutely needs a particular file to be included, PHP also has the require keyword, which, if called on a file that does not exist, will halt script execution with a fatal error. However, the chances of you telling PHP to include a script and it not being a problem if that script cannot be located are slim, so favour require.

The most common way to use these include files is as storage for common functions, object definitions, and layout code. For example, if your site always has the same header HTML to it, you can start each of your pages with this:

<?php    include 'header.php';    ...[snip]...

That way, whenever you want to change the header of your site, you just need to edit one file. Two more keywords that are likely to be of use are include_once and require_once, which operate in the same way as include and require respectively, with the difference that they will only include a file once, even if you try to include it several times. Include_once and require_once share the same list of "already included" files, but it is important to note that operating systems that are case sensitive, such as Unix, are able to include_once/require_once a file more than once if the programmer uses varying cases for their filenames. For example:

<?php    include_once 'bar.php';    include_once 'BAR.php';    include_once 'Bar.php';?>

On Unix, that will attempt to include three entirely different files, because Unix is case sensitive. The solution is simple: use lower case filenames for everything!

Note that if PHP cannot find a file you try to include() or require() in the same directory as the script that is running, it will also look in its standard include path. This is defined in your php.ini file as the include_path directive.

…Including other files

Page 22: PHP Building Blocks

Although you would obviously rather that your PHP scripts always execute correctly from the start of the script to the end of the script, there are a variety of reasons why they might not. Put succinctly, these reasons are:

You've screwed up somewhere, and PHP cannot execute your code.

PHP has screwed up somewhere due to a bug, and cannot continue

Your script has taken too long to execute, and gets killed by PHP Your script has requested more memory than PHP can allocate,

and gets killed by PHP To be brutally honest, the first situation is unequivocally the most

common. This will change a little as your skill with PHP improves, but the first situation is still the most common even amongst the most veteran programmers!

Abnormal script termination