Search This Blog

PHP tutorial for beginners explained with examples


PHP is a server side general purpose scripting language, most widely used for developing web applications. It supports various databases namely MySQL, FbSQL, GeoIP, YAZ databases and so on. Rasmus Lerdorf, a Greenlandic-Danish programmer created PHP in the year 1994. It is easy to learn. No prior programming language experience is required.

PHP file terminates with an extension .php .

Lets begin learning with an example,
<!DOCTYPE HTML>
<html>
    <body>
        <?php
            echo "Hello world, PHP script goes here!!";
        ?>
    </body>
</html>

Place the above piece of code in a file with an extension .php. When it gets executed, the text inside double quotes gets displayed on the terminal. In this example, PHP code begins with <?PHP and ends with ?>

PHP comments

PHP supports both single line and multi line comments that can be embedded in a .php webpage. Single line comments begin with double forward slash or single hash and multi-line comments can be embedded within special characters as shown below. Usage of comments is similar to C, C++, PERL and so on which makes easy to remember. 
<?php
    echo 'This is a test'; // This is a single-line c++ style comment

    echo 'One Final Test'; # This is a one-line unix shell-style comment
    /* This is a multi line comment
       yet another line of comment */  
?>

PHP conditional statements

if statement: It will execute the statements mentioned in the if block only when the condition is satisfied.

Syntax:
if (condition)
{
PHP statements
}

Ex:
if ($a>10)
{
echo $a;
}

if....else statement: It will execute the statements mentioned in if block only when the condition is satisfied else it will execute the statements mentioned in else block.

Syntax:
if (condition)
{
PHP statements
}
else
{
PHP statements
}
Ex:
if ($a>10)

{
echo $a;
}
else
{
echo "$a is less than 10";

}

if....else if....else statement: Multiple if else conditions are used to check multiple conditions.

Syntax:
if (condition1)
{
PHP statements
}
else if (condition2)
{
PHP statements
}
else
{
PHP statements
}
Ex:
if ($a>10)
{
echo "$a is greater than 10";
}
else if ($a<5)
{
echo "$a is less than 5";
}
else 
{
echo "$a lies between 5 & 10";
}

PHP loops

Loops execute the same block of code a specified number of times until the specified condition is true. In PHP, we have four looping statements:

while loop 
do....while loop 
for loop 
foreach loop 
break and continue keywords can be used to control the above loops

while loop: Iterates through the same block of code when the specified condition is true

Syntax:
while (condition)
{
code to be executed;
}

Ex:
<?php
$i = 1;
while ($i<5)
{
echo "$i";
$i++;
}
?>
The value 1 is stored in variable $i ($i=1;). Value stored in $i is compared with value 5 in while condition. When condition is true, it enters the loop and the value of i gets incremented in the loop. Now again the value stored in $i is compared with value 5 and looping continues till $i reaches value 5. Once $i increments to value 5, the condition in while loop becomes false and it comes out of the loop.
Output:
1
2
3
4

do....while loop: Executes the block of code once and then the condition is checked. It continues the looping(iteration) while the specified condition is true.

Syntax:
do
{
code to be executed;
}
while (condition);

Ex:
<?php
$i = 1;
do
{
echo "$i";
$i++;
}
while ($i<5);
?>
To understand this example, the same block of code used in while loop is used here. Since the condition is tested after the execution, it will result in extra output 5.
Output:
1
2
3
4
5

for loop: It is used when you know how many times you want to execute a single statement or a block of statements in advance.

Syntax:
for ( initialization : condition : increment )
code to be executed;
}

initialization: It is used to initialize the counter. The first statement that gets executed in the loop.
condition: Gets evaluated during every iteration of the loop. If it results in TRUE the loop continues to execute else it stops execution.
increment: Used to increment the counter. The last statement that gets executed at the end of the iteration.

Ex:
<?php
for ( $ctr = 0 ; $ctr < 4 ; $ctr++ )
echo "The value of counter is $ctr";
}
?>

The counter is initialized to 0 and it iterates four times before coming out of the loop. During every iteration, counter gets incremented by one.

Output:
The value of counter is 0
The value of counter is 1
The value of counter is 2
The value of counter is 3

foreach loop: Iterates throughout the elements of an array. Array elements will be an input to the loop and array pointer gets incremented by one during every iteration. The iterations stop after executing the statements with the last element in an array as input.

Syntax:
foreach ( array as $value )
code to be executed;
}

Ex:
<?php
$a = array(1,2,3);
foreach ($a as $value)
{
echo "$value"
}
?>

This example results is displaying all the elements of an array.

Output:
1
2
3

The break and continue keywords are used to control the loops. It can be used in any of the looping blocks.
break: This keyword is used to terminate the execution of loop. It is situated inside the body of the loop.

Ex:
<?php
for ( $ctr = 0;  $ctr < 10; $ctr++)
{
if ( $ctr == 4) break;
}
echo "Now the value of counter is $ctr";
?>

This example shows the termination of for loop when the counter value reaches 4. After termination from the loop, the statements following it will execute.
Output:
Now the value of counter is 4

continue: Similar to break with the only difference that instead of terminating the loop it is used to skip the particular iteration and continue in looping. 

Ex:
<?php
for ( $ctr = 0 ; $ctr < 3 ; $ctr++)
{
if ( $ctr == 2 ) continue;
echo "Value of counter is $ctr";
}
?>

It will skip the statement Value of counter is 2 and continues looping. 

Output:
Value of counter is 0
Value of counter is 1
Value of counter is 3

PHP Arrays

Array holds more than single value. It is usually used to store the list of values.
There are three types of arrays, namely;
  • Numeric arrays will have numbers as an index
  • Associative arrays will have keys as an index
  • Multidimensional arrays contains arrays as its value
Numeric Array
<?php
$first = array ( "one", "two", "three");
$second[0] = "one" ; $second[1] = "two" ; $second[2] = "three" ;
?>

Here two arrays $first and $second are being initialized with values. In the first case, the indexing happens automatically. Second case shows how to assign values to particular index values. The value can be number or string.

Associative array:

<?php
$third = array ( "dil" ->  500, "mange" -> 600, "more" -> 700 );
?>

In this case, dil, mange, more acts as keys/indexes and 500, 600, 700 as its values. The keys can be number or string.

Multidimensional Array:


<?php 
$marks = array( "xyz"  => array ( "p" => 99, "m" => 100, "c" => 100 ), 
"mno" => array ( "p" => 100, "m" => 91, "c" =>98 ), 
"abc"  => array ( "p" =>  98, "m" => 98, "c" => 88 ) );
/* Accessing multi-dimensional array values */
echo "Marks of xyz in physics : $marks['xyz']['p']\n"; 
echo "Marks of mno in maths : $marks['mno']['m']\n"; 
echo "Marks of abc in chemistry : $marks['abc']['c']";  


Output: Marks of xyz in physics: 99 Marks of mno in maths: 91 Marks of abc in chemistry: 88
Lets learn more about arrays with the below examples.
Ex:
$num = array ( 8, 9, 5, 6, 3, 2 );
$str = array ("ab" => 89, "cd" => 56, "bc" => 32, "de" => 28 );
count() - Gives the length of an array
echo "count($num)";
Output:  6
sort() - sorts the array values in ascending order.
echo "sort($num)";
foreach($num as $x)
{
echo "$x";
}

Output: 2,3,5,6,8,9
rsort() - sorts the array values in descending order.

echo "rsort($num)";
foreach($num as $x)
{
echo "$x";
}
Output: 9,8,6,5,3,2
asort() - sorts the associative array values in ascending order.

Ex: 
echo "asort($str)";
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}

Output: 
Key=de, Value=28
Key=bc, Value=32
Key=cd, Value=56
Key=ab, Value=89

ksort() - sorts the associative array keys in ascending order.

Ex: 
echo "ksort($str)";
foreach($age as $x=>$x_value)
{
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}

Output: 
Key=ab, Value=89
Key=bc, Value=32
Key=cd, Value=56
Key=de, Value=28

arsort() - sorts the associative array values in descending order.

Ex: 
echo "arsort($str)";
foreach($age as $x=>$x_value)
{
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}

Output:
Key=ab, Value=89
Key=cd, Value=56
Key=bc, Value=32
key=de, Value=28

krsort() - sorts the associative array keys in descending order.

Ex: 
echo "krsort($str)";
foreach($age as $x=>$x_value)
{
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";

}

Output:
Key=de, Value=28
Key=cd, Value=56
Key=bc, Value=32
Key=ab, Value=89

PHP File handling tutorial

fopen(): Opens the file.

Ex:
<?php
$fp = fopen ("filename.txt","w");
?>

The first argument in fopen(), specifies filename and the second specifies the mode. Them modes can be r, r+, w, w+, a, a+, x, x+.

r : Opens for reading. 
r+: Opens for both reading and writing.
w : Opens for writing, creates a new file if it doesn't exist. 
w+: Opens for both reading and writing, creates a new file if it doesn't exist.
a :  Appends the content by writing from the end of file.
a+: Reading and appending the content by writing from the end of file.
x :  Creates for writing, returns FALSE if file already exists.
x+: Creates for writing and allows reading, returns FALSE if file already exists.

fclose(): Closes the opened file.
Ex:

<?php
fclose($fp);
?>
It will close the opened file. The file pointer will become an argument in fclose().

feof(): Checks for the end of file.

Ex:

<?php
if (feof($fp))
echo "Pointer reached to end of the file"
?>

It is used when length of file is unknown. When file pointer reaches the end of file, it becomes feof() becomes TRUE.

fread(): Gives the entire file content at once.

Ex:

<?php
$file = fopen("filename.txt", "r");
echo fread($file);
fclose($file);
?>

fgets(): Gives the content of file line by line. 

Ex:

<?php
$file = fopen("filename.txt", "r");
while(!feof($file))
{
echo fgets($file)."<br>"; 
}
fclose($file);
?>

After the call, pointer moves to next line.


fgetc(): Gives the content of file character by character. 

Ex:

<?php
$file = fopen("filename.txt", "r");
while(!feof($file))
{
echo fgetc($file)."<br>";
}
fclose($file);
?>

After the call, pointer moves to next character.

filesize(): Gives the size of file in bytes.

Ex:

<?php
$file = fopen("filename.txt", "r");
echo filesize($file);
fclose($file);
?>