PHP – Hypertext Preprocessor

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

PHP is the common name for Hypertext Preprocessor.
The first “P” stands for “PHP,” and the first “P” of that stands for “PHP” again, makes it a recursive acronym.

PHP originally reffered to as Personal Home Page, but later on renamed as Hypertext Preprocessor when the language was commonly being used on the web, at version 3.0.

PHP is a behind the scene scripting language that was originally designed for web development, to produce dynamic and interactive web pages.

It is generally used with HTML and runs on a web server. This web server needs to be configured to process PHP code and create web page content from it. PHP is Open Source and free to use, so it can be deployed on almost all web servers and near about on every operating system and platform.

PHP has evolved to include a command line interface capability and can also be used in standalone graphical applications. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in.

What You Should Already Know
PHP learning requires some basic knowledge of
HTML/XHTML
Javascript

Since using PHP for web development will require embedding it into HTML and some JavaScript may be used somewhere here and there. So its better to have some working knowledge of both. If you don’t have then you may learn them in the meantime.

MySQL

  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use


PHP + MySQL

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

PHP If Condition

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

The If Statement

This statement executes a piece of code only when a condition is true.

Syntax

    if (condition) code to be executed if condition is true;
    For eg:

    <html>
    <body>
    <?php
    $d=date(”D”);
    if ($d==”Fri”) echo “Today is Friday!”;
    ?>
    </body>
    </html>

The if…else Statement

This is a two way condition evaluation, in which there are yes and no both lead to different code block.

We just add one else condition in the above if statement.

Syntax

    if (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
    For eg:

    <html>
    <body>
    <?php
    $d=date(”D”);          if ($d==”Fri”)
    echo “Today is Friday!”;         else
    echo “Today is not Friday!”;
    ?>
    </body>
    </html>

If more than one line should be executed, then the lines should be enclosed within curly braces:

    <html>
    <body>
    <?php
    $d=date(”D”);
    if ($d==”Fri”)
    {
    echo “Hello!<br />”;
    echo “Today is Friday!”;
    }
    ?>
    </body>
    </html>

The if…elseif….else Statement

This construct is used when there are more conditions than just true or false.

When PHP evaluates If…elseif…else statement it first sees if the If statement is true. If that test comes out to be false it then checks the first elseif statement.

If then also the result comes out to be false it will check the next elseif statement, if there exists any more otherwise, it will evaluate the else segment, if one exists.

Syntax

    if (condition)
    code to be executed if condition is true;
    elseif (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
    For eg:

    <html>
    <body>
    <?php
    $d=date(”D”);        if ($d==”Fri”)
    echo “Today is Friday!”;        elseif ($d==”Sun”)
    echo “Today is Sunday!”;        else
    echo “Today is neither Friday nor Sunday!”;
    ?>
    </body>
    </html>

PHP – How to Start With?

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

Every language has some rules to how to write them or all languages has some defined words which must be used to make a meaningful sentence. Like that PHP too has some rules that must be followed to write properly structured code, which could be understood by the PHP interpreter.

PHP is similar to most of the other programming languages (C, Java, and Perl) in syntax and semantics.

All PHP code is contained within a tag. As PHP is less often used stand alone so all the PHP code is written within a tag which marks the beginning and the end of PHP code.

<?php
//Your PHP code goes here
?>

Or you can use the shorthand

<?
//Your PHP code goes here
?>

However, if you are using multiple scripting languages then you must use the former to avoid confusion and mixing of all the codes.

PHP code written outside this tag will not be interpreted and will be directly displayed on the browser as some jumbles.

A PHP block can be anywhere in your page.

Saving Your PHP Pages

A PHP file is a file with extension “.php”, “.php3″, or “.phtml”. It can be written in any SDI (Single Document Interface) like notepad, and save with any of the three extensions.PHP files can contain text, HTML tags and scripts.

PHP scripts runs on the server, when a browser sends request PHP files are returned to the browser as plain HTML

If you have inserted PHP into your HTML page, then you must save the file with a .php extension, instead of the standard .html extension, then only it will be interpreted as some script otherwise it will be displayed as it is.

Conditional Statements

Posted by tutor | Posted in PHP Tutorial | Posted on 04-08-2010-05-2008

0

Conditional statements are used to evaluate some conditions and perform different actions based on the outcome.

You can use conditional statements in your code to do this.

PHP provides the following conditional statements:

  • If statement – execute the piece of code only if a specified condition is true.if (condition) code to be executed if condition is true;
  • If…else statement – this statement executes a two way condition, where the true part does something else and the false part executes something else.if (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
  • If…elseif….else statement – if there are multi-way condition, where there are several blocks of code to be executed based on different conditions.if (condition)
    code to be executed if condition is true;
    elseif (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
  • Switch statement – this statement is used to select one of many blocks of code to be executedswitch (n)
    {
    case label1:
    code to be executed if n=label1;
    break;
    case label2:
    code to be executed if n=label2;
    break;
    default:
    code to be executed if n is different from both label1 and label2;
    }

Arrays

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

An array is a collection of similar type of values. It is a data structure which stores one or more similar type values as a single value. In PHP arrays are actually maps, ie each key is mapped to a value.

We are assuming that you have a basic knowledge of programming, so you must be knowing what are arrays.

If you are new to programming, then it may confuse you, as till now one variable can store only one value but this variable can store multiple values.

You may think an array as a container with many spaces where you can fill data according to your choice. Arrays group similar kind of data as it doesn’t make sense to store a set of like values in different variables.

For eg if you want to store your marks of different subject, if you have only 5 subjects then you can store them separately, but if you are having twenty or thirty subjects or even more then it will look very clumsy to use so much variables moreover it will be very tough to manage such number of variables.

You can define array using square brackets as:

$my_array[];

You can assign values to the array elements as:

$marks[0]=20;
$ marks [1]=10;

Araay can be understood using the key / value structure. Keys are the numbers specified in the array and the values are the marks. Each key of an array is associated with a value that we can manipulate and reference.

The general form to set the key of an array equal to a value is:

$array[key] = value;

In other programming language you can only provide integer as the key value for the array but in PHP you can also specify a string as the key. This later type is referred to as Associative array

PHP arrays are mostly used with loops, which we will be discussing soon.

In PHP you have the following types of arrays:

  • Numeric array – An array with a numeric index
  • Associative array – An array where each ID key is associated with a value
  • Multidimensional array – An array containing one or more arrays

Numeric Arrays

A numeric array is the most common type of array, which stores each array element with a numeric index. This kind of array is found in all programming languages.

There are two methods to create a numeric array.

  1. In the following example the index are automatically assigned (the index starts at 0)<$marks=array(20,10,30,40)
  2. In the following example we assign the index manually:$marks[0]=20;
    $ marks [1]=10;
    $ marks[2]=30;
    $ marks [3]=40;

Associative Arrays

In an associative array the key used is a string value. We have already seen how you can store the marks of the subjects you studied till now using an array. But there was a slight problem, you will not be able to distinguish which mark is for which subject unless you write it somewhere that which key value stands for which subject. This is extra information you will have to manage somewhere outside your program. Rather if there have been a way to store them together then it will lessen your burden.

Associative array is such a way. The key values of this array are strings.

$marks[“Physics”]=20;
$marks[“Chemistry”]=30;
$marks[“Biology”]=40;
$marks[“Maths”]=60;

Multidimensional Arrays

A multidimensional array is an array of arrays. In a multidimensional array, each element in the main array is also be an array. And each element in the sub-array can be an array, and so on.

$families = array (”Fruit”=>array (”Mango”,”Apple”,”Strawberry”),
“Animals”=>array (”Lion”,”Tiger”),
“Birds”=>array (”Eagle”,”Peacock”,”Penguin”)
);

The arrays and sub-arrays can be referred to as

$families['Fruit'][2] will refer to Strawberry.

Working with String variables

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

A string variable is used to store and manipulate character strings.

PHP provides some pre defined functions to manipulate string variables. There are someoperators also which directly work on strings.

For eg:

<?php
$txt=”Its PHP”;
echo $txt;
?>

Output:

Its PHP

We can use strings directly within double quotes or we can assign them to some variable and can use them through variables.

The Concatenation Operator

PHP provides an operator to manipulate string variables directly. This is called the concatenation operator represented by a “.” (dot).
The concatenation operator (.), as the name implies, concatenates two strings, ie it joins two or more strings.

For eg:

<?php
$txt1=”Its PHP!”;
$txt2=” So easy to use!”;
echo $txt1 . $txt2;
?>

Output:

Its PHP! So easy to use!

The strlen() function

Like in other languages PHP defines the strlen() function, which returns the length of a string.

For eg:

<?php
echo strlen(”Its PHP!”);
?>

Output:

8

This function can be useful in various string operations like matching two strings or finding some string in a large text where the loop counter should iterate till the last character of the text only. Various other applications can also use this function.

The strpos() function

The strpos() function searches a given character within a string.

If the character is found, this function will return the position of the first match. If no match is found, it will return FALSE.

For eg:

<?php
echo strpos(”Its PHP!”,”PHP”);
?>

Output:

4

The position of the string “world” is 6, as the counter starts from 0.

Combining Arithmetic & Assignment Operators

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

We often need to increment a variable by a fixed amount. For eg a variable which is being used to count something, may be a counter for a loop or some other purpose, we need to constantly increment it by 1.

    $count = $count + 1;

However, there is another way for doing this.

    $counter += 1;

This combined assignment/arithmetic operator would accomplish the same task as the above code.

Although this combined operator shortens the code but sometimes for those who are not accustomed to such programming constructs, this may create confusion and may make the code unreadable.0

    Operator Description Example Expanded Form
    += Plus Equals $x += 2; $x = $x + 2;
    -= Minus Equals $x -= 4; $x = $x – 4;
    *= Multiply Equals $x *= 3; $x = $x * 3;
    /= Divide Equals $x /= 2; $x = $x / 2;
    %= Modulo Equals $x %= 5; $x = $x % 5;
    .= Concatenate Equals $my_str.=”PHP”; $my_str = $my_str .”PHP”;

PHP Variables

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

A variable is something whose value can be changing, or the other way round, a variable is used to store some values which are not constant. These values can be anything, like string, any integer value etc.

After declaring a variable you can use it again and again in your script.

Variables are declared using a $ sign. In PHP variables are typed according to the value they contain, so we don’t write any type specifier while declaring a variable.

    $var_name = value;

If you forget putting a dollar sign before the name of a variable, it won’t work in PHP

PHP is a Loosely Typed Language.It internally converts a variable to the same type as the data type of its value. You can declare a variable only when you need one. No previous declaration is needed.

Naming Rules for Variables

PHP has variable declaration rules similar to other programming languages:

  • variable name can only start with a letter or an underscore “_”
  • variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
  • variable name can not have spaces. If a variable name is of more than one word, it should be separated with an underscore, or with capitalization
    like “$my_string” or “$myString”

Like other programming languages, variable names in PHP also are case-sensitive, so be sure to use the exact capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP.

White Space

Like HTML, whitespaces are ignored in PHP. You can put any number of whitespaces may be to properly indent your code, and all the whitespaces will be ignored by the PHP interpreter.

Using Comments in PHP

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

Comments are used in every programming language for making the code better to understand.

The PHP comment syntax, like other programming language, begins with a special character sequence and all text that appears between the start of the comment and the end will be ignored.

Comments are written to have better readability and understandability of the code. They provide information about the code, or sometimes omits a part of code which may not be used at present ar for a particular scenario like for testing.

A comment’s main purpose is to serve as an informative note to you, the web developer or to others who may view your source code.

PHP’s comments are not displayed to the visitors visiting the website, even if they view the page’s source. The only way to view PHP comments is to open the PHP file for editing. So for this reason, the PHP comments are useful only for the developers, unlike HTML, where the visitor can also view the comments.

PHP Comments is of two types

  • Single line – // or # followed by the line to be commented out.
  • Multiple lines – /* */ is used to mark the beginning and the end of multiple lined comment.

PHP Comment Syntax: Single Line Comment

The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment. To do a single line comment type “//” or “#” and all text to the right will be ignored by PHP interpreter.

For eg:

<?php
echo “It’s so good to be here!”;                    // This will print out It’s so good to be here!
echo “<br />There are comments on this page but you can’t see them…!!!”;
// echo “This is not for you”;
// echo “My name is Tutor!”;
# echo “I am the PHP programmer”;
?>

Output:

It’s so good to be here!
There are comments on this page but you can’t see them…!!!

Some of our echo statements were not evaluated because we commented them out with the single line comment.

This type of line commenting is often used for quick notes about complex and confusing code or to temporarily remove a line of PHP code, may be for testing.

PHP Comment Syntax: Multiple Line Comment

The multi-line PHP comment can be used to comment out multiple lines of code or writing multiple line comments. The multiple line PHP comment begins with ” /* ” and ends with ” */ “.

For eg:

<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo “It’s so good to be here!”;
/* echo “My name is Tutor!”;
echo “I am the PHP programmer!”;
*/
?>

Output:

It’s so good to be here!

Good Commenting Practices

The best commenting practice is to use them, anywhere and everywhere, where there is a need to put some extra detail, so that everyone viewing the code can atleast understand the structure.

Use single line comments for quick notes about a tricky part in your code and use multiple line comments when you need to elaborate on some function or some construct.