PHP Tutorial - An Introduction To PHP

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 33

PHP Tutorial - An Introduction to PHP

Page 1 of 1

This tutorial moves a step further from the basic HTML, and it will enhance your art of making
good web pages with the use of PHP. Until recently, many websites were made only with the use
of HTML, but the recent dot com revolution has changed the scenario. In today’s world, more
and more scripting languages have come into existence and PHP is one of them. It is the easiest
scripting language and yet the most powerful.

You should be having a basic understanding of WWW, HTML, and basics of building web
pages before you learn the usage and handling of PHP.

What is PHP?

PHP stands for Hypertext Preprocessor. PHP is an open source server side scripting language
that is especially suited for web development and can be embedded into HTML. The PHP scripts
are executed on the server, not on the user’s browser, so there are no compatibility issues. PHP
supports many databases like MySQL, Oracle, and Sybase. Since PHP is open source software,
therefore it is free to download and use. Due to this it is quickly becoming the most famous
scripting languages on the internet.

Why PHP?

Many questions must be coming to your mind, like:

Why should I learn a scripting language?

Why should I choose PHP over other languages?

• Learning a scripting language can open up huge possibilities for your website. With the
use of scripts you can add many new interactive features like feedback forms, guest
books, message boards, counters and many more advanced features. This will give your
website a more professional image.
• PHP is one of the most powerful scripting languages which run on different platforms. It
is compatible to almost all the servers used today. The most striking features of PHP are
that it is FREE to download, easy to learn, and runs efficiently on the server side.

What does a PHP File contain?

• PHP files may contain text, HTML tags and scripts.

• PHP files are returned to the browser as plain HTML.

• PHP files have an extension of “.php”, “.php3”, or “.phtml”.

What is needed to run PHP?


PHP is a server side scripting language. This means that, the users will not need to install new
software but your web host will need to have PHP set up on their server.

• Install an Apache server on your machine. You can download it from


http://http.apache.org/download.cgi.

• Install PHP on your machine. You can download it from


http://www.php.net/downloads.php.

Now that you have installed all the support software for running PHP, you are ready to learn how
to do a PHP script.

Writing a PHP script is very simple. No special software is needed, except a text editor like
Notepad in which the script is written. You have to run that code on your web browser and you
are ready with your first PHP script.

The First Script

A PHP file normally contains HTML tags and some PHP scripting code. A PHP scripting block
always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in
the document.

In PHP scripting each line of code must end with a semicolon (;). The semicolon acts as a
separator and is used to distinguish between two sets of instructions.

There is a PHP script in the example given below. This script will display the words “Welcome
to expertrating!” in the web browser. There are two basic statements to output text on the
browser with PHP: echo and print. In the example given below, the echo statement is used to
display text.

Example
<html>
<head>
<title>Example</title>
</head>
<body>

<?php
echo "Welcome to expertrating!";
?>

</body>
</html>
Output

How to run your PHP script?

• Save that script in the web server’s root directory.

• Open your web browser and type “//localhost/directory name/filename.php” and then
press enter.

• By doing this the script will run in your browser.

Variables

Different languages have different ways of defining a variable. Similarly, in PHP variables are
defined in a unique manner. All variables in PHP start with a $ sign symbol. Variables may
contain strings, numbers, or arrays.
If you want to assign a string to a variable, then you have to put that string into quotes “ “ like:
“Hello! How are you?”. If you want to assign a number to a variable then there is no need to
include it into the quotes.

The code to display a variable on the screen is same as the code to display normal text. The
variables are also displayed with the echo command e.g. echo $abc.

This is an example in which a string is assigned to a variable, which is further displayed on


the web browser.

Example
<html>
<head>
<title>Example</title>
</head>
<body>

<?php
$txt ="Hello and Welcome to expertrating.";
echo $txt;
?>

</body>
</html>

Output:
This is an example in which a number is assigned to a variable, which is further displayed on the
web browser.

Example
<html>
<head>
<title>Example</title>
</head>
<body>

<?php
$txt=56;
echo $txt;
?>

</body>
</html>

Output:
In order to concatenate two or more variables together while displaying the result on screen, use
the dot (.) operator.

Example
<html>
<head>
<title>Example</title>
</head>
<body>

<?php
$abc="Welcome to expertrating!";
$xyz=56;
echo $abc . " " . $xyz;
?>

</body>
</html>

Output:
Comments

In PHP, if a single line comment has to be made we use two backslashes //. If a double line or
large comment block has to be made then it has to start with a /* and end with a */.

Example
<html>
<body>

<?php
//This is a comment
/*
This is
a comment
block
*/
echo "You have Learned about Comments.";
?>

</body>
</html>
Output:

By now, you must have started writing those scripts and started working on PHP. Now, it’s time
for you to learn about the operators available in PHP. An operator is something in which one or
more values are fed and it gives another value as a result.

In general there are three types of operators:

• Unary – it operates on only one value.

• Binary – it operates on two or more than two values.

• Ternary – it is used to select between two expressions depending on the third one.

There are many types of operators in PHP; some of them are useful but some are not. In this
tutorial we will be studying about the most useful operators in PHP, which are:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

Arithmetic Operators

Addition (+)
$a=20;

$b=10;

$c=$a+$b;

Result = 30

Subtraction (-)

$a=15;

$b=10;

$c=$a-$b;

Result = 5

Multiplication (*)

$a=5;

$b=2;

$c=$a*$b;

Result = 10

Division (/)

$a=30;

$b=2;

$c=$a/$b;

Result = 15

Modulus (%)

$a=5;

$b=2;

$c=$a%$b;
Result = 1

Increment (++)

$a=5;

$a++;

Result = 6

Decrement (--)

$a=5;

$a--;

Result = 4

Assignment Operators

Equal to (=)

$a=$b;

Is same as $a=$b;

Plus equal to (+=)

$a+=$b;

Is same as $a=$a+$b;

Minus equal to (-=)

$a-=$b;

Is same as $a=$a-$b;

Multiply equal to (*=)

$a*=$b;

Is same as $a=$a*$b;

Divide equal to (/=)


$a/=$b;

Is same as $a=$a/$b;

Modulus equal to (%=)

$a%=$b;

Is same as $a=$a%$b;

Comparison Operators

Equal to (==)

3==5;

Result: False

Not equal to (!=)

3!=5;

Result: True

Greater than (>)

3>5;

Result: False

Less than (<)

3<5;

Result: True

Greater than or equal to (>=)

3>=5;

Result: False

Less than or equal to (<=)

3<=5;
Result: True

Logical Operators

And (&&)

$a=5;

$b=2;

($a>4 && $b<3);

Result: True

Or (||)

$a=7;

$b=8;

($a<5 || $b<5);

Result: False

Not (!)

$a=5;

$b=5;

!($a==$b);

Result: False

Conditionals and Looping

In the previous chapters the basics of PHP have been explained. With this you must be well
versed with the basic idea of PHP. Now we will be taking a step forward and moving on to the
learning of the conditional statements and looping structures. These conditional statements and
looping structures give you more flexibility in writing a PHP script.

Conditional Statements

Conditions and conditional statements are a part of every programming language and scripting
language. There are times when you want to perform different actions for different decisions. In
this you have to use conditional statements, so that the correct decision should be made.
Consider a situation if you want to greet every visitor on your site on 25 th December with Merry
Christmas. In order to achieve this you do not have write a code on Christmas displaying Merry
Christmas. This can be done well in advance as you can always write a conditional statement that
if date is 25 th December then Merry Christmas should be displayed. So, with the help of
conditional statements job done, well in advance.

In PHP there are two conditional statements:

• If then else statement – This statement is used to execute a specific set of code if the
condition is true and other set of code should be executed if the condition is false.

• Switch statement – This statement is used when you want that one of many lines of
codes should execute.

If Statement

The “if else” statement is used if one set of code has to be executed when the condition is true
and another set of code has to be executed when the condition is false.

Syntax
If (condition)

Statements to be executed if code is true;

else

Statements to be executed if code is false;

In the following example x is compared with y. If x is greater than y then it will display x is
greater then y else it will display y is greater than x.

Example
<html>

<body>

<?php

$x=10;

$y=15;

if ($x>$y)

echo "x is greater than y";


Else

echo "y is greater than x";

?>

</body>

</html>

Output

In the if statement if you want to execute more than one line when the condition is true then
those lines should be put in curly braces.

Example
<html>

<body>

<?php

$x=10;

if ($x>=10)

{
echo "Hello<br/>";

echo "The day is over for you.<br/>";

else

echo "Hello<br/>";

echo "You still have to work.<br/>";

?>

</body>

</html>

Output

Switch Statement
The “switch” statement is another useful conditional statement. It is used when one of the many
blocks of code has to be executed. When the switch statement is used then it checks for all the
conditions at once and it is also a good programming practice.

In the switch statements break is used to prevent the code from running into the next case
automatically.

Syntax
switch (expression)

case label1:

code to be executed if the expression = label1;

break;

case label2:

code to be executed if the expression = label2;

break;

default:

code to be executed if the expression is different from both label1 and label2;

break;

In the following example there is a single expression that is evaluated once. After this the value
of the expression is compared with the value of each case in the structure. If the value in any of
the cases gives a match, then the block of code associated with that structure is associated. If the
value does not match with any of the cases then the default case is executed.

Example:

<html>
<body>

<?php

$input = 10;
echo "Working for $input hours<br />";

switch ($input)

case 6:

echo "Your salary is $600";

break;

case 8:

echo "Your salary is $800";

break;

case 10:

echo "Your salary is $1000";

break;

case 12:

echo "Your salary is $1200";

break;

default:

echo "How much do you work?";

break;

?>

</body>

</html>

Output
Looping

In the previous section you learned about the conditional statements. In this section you will be
learning about the looping structures. The looping statements are used to execute a same block of
code a specified number of times.

The various looping statements available in PHP are:

While – it loops through a block of code if a specific condition is true and it comes out of the
loop only when that condition becomes false.

Do while – in this it loops through a block of code at least once, then it checks for the condition
and loops as long as that condition is true.

For – it loops through a block of code a specified number of times.

Foreach – it loops through a block of code for each element in an array.

While Loop

The “while” loop, is the simplest type of loop in PHP. They work the same in PHP as they do in
other languages. The “while” statement executes a block of code if a specific condition is true
and it comes out of the loop only when that condition becomes false.

Syntax
while (condition)
code to be executed;

In the following example we are using the while loop which checks for the condition and
executes the loop till the condition is true.

Example
<html>

<body>

<?php

$a=1;

while($a<=4)

echo "Welcome to floor " . $a ."<br/>";

$a++;

?>

</body>

</html>

Output:
</html>

Output
Foreach Loop

The foreach loop works only on arrays. It loops through a block of code for each element in an
array. On each loop the value of the current element in array is assigned to $value and the array
pointer is advanced by one. Similarly in the next loop the value of the next element in array is
assigned to $value and the array pointer is advanced by one. This process is repeated till the end
of the array.

Syntax
foreach (array as value)

code to be executed;

In the following example the values of the given array will be printed by the loop.

Exampl
<html>
<body>

<?php
$arr=array("hello", "how", "are", "you");
foreach ($arr as $value)
{
echo "The value is: " . $value . "<br />";
}
?>

</body>
</html>

Output
In this chapter you will be getting technical know how of functions. Functions are useful in any
type of programming language. Whenever you want to use a particular piece of code over and
over again, it is very useful to put that code in a function. This is done so that the code can be
reused easily. Another use of using functions is that whenever there is an error in the code, and
then it has to be corrected only at one place; in the function. With the use of functions, the entire
code can be understood easily.

Declaring Functions

Creating your own function in your script is a straightforward task. It is like creating a function
in any other language. The functions in PHP begin with the keyword“function” which is
followed by the function name. Following the function name there is a set of parenthesis which
contains the parameters to be passed. These parameters are an optional set of variables passed to
the function.

Syntax
function <name of function> ([$var1 [= constant]], [$var2 [= constant]], …)
{

Body of the function;

Your First Function

Now that you have got an idea of th2e functions, you are ready to start with functions. In the
following example the string “Welcome to expertrating!” will be printed five times on the
browser with the help of functions. By writing a single code once in a function, we can call the
same function again in a script.

Example
<html>
<body>

<?php

function fundisp()

{
for($i = 0; $i < 5; $i++)

{
echo "Welcome to expertrating!<br/>";
}
}

echo "After this statement the function will be called.<br/><br/>";


fundisp();
echo "<br/>";
echo "This statement is printed after the function has been called.";
echo "<br/>";
?>

</body>
</html>

Output
Passing Parameters to Functions

In this section we will be discussing about how to pass parameters to a function in PHP. A
parameter of a function is a piece of data that a function requires to execute. If we define
parameters formally then, function parameters are represented by variable names which are
located within the parenthesis of the function definition.

In the following example of passing parameters to functions we will be displaying the string
“Welcome to expertrating!.” The difference that this example has got with the previous example
is that, in this example the number of times the text will be displayed is not fixed, rather that
number is passed as a parameter when the function is called.

Example
<html>
<body>

<?php

function fundisp($num)
{
for($i = 0; $i < $num; $i++)
{
echo "Welcome to expertrating!<br/>";
}
}

echo "After this statement the function will be called.<br/><br/>";


fundisp(7);
echo "<br/>";
echo "This statement is printed after the function has been called.";
echo "<br/>";
?>

</body>
</html>

Output

Functions within Functions

In PHP a function can be embedded within a function. If a function is embedded within a


function, then in order to call that function we have to first call the parent function. If we directly
try to call the embedded function it will give an error.

In the following example the function func1 is called first and then the function func2 is called.
If the function func2 is called without calling the function func1 then it will give an error.
Example:
<html>
<body>

<?php
function func1()
{
function func2()
{
echo "Welcome to expertrating.com! <br/><br/>";
echo "func2() is called after calling func1().\n";
}
}

//func1 will be called first.

func1();

//func2 will be called after calling func1.

func2();
?>

</body>
</html>

Output
Returning Values

In PHP the values are returned from a function by using the “return” statement. With the use of
return any type can be returned including string, lists and objects. The return statement ends the
execution of the function and passes back the control to the line from which it was called.

In the following example we will see the use of return statement. In this example a function is
written which checks for the smaller value. It returns a “yes” if the first value is smaller than the
second one and a “no” if its not.

Example:
<html>
<body>

<?php

function lessthan($a, $b)

{
if($a < $b)

return "Yes";

else

return "No";

$xyz = lessthan(26,22);

echo "Is 26 less than 22?----$xyz";

?>

</body>
</html>

Output
Scope of the Variables

When a variable is declared in a function then it remains local to that function. This means that,
that variable cannot be accessed from outside the function or by other functions. It is helpful
when two variables of same name have been declared in different functions. This prevents you
from accidentally overwriting the contents of a variable.

In the following example you will see how a variable defined in a function cannot be accessed
from outside the function.

Example

<html>
<body>

<?php
function abc()
{
$a = "Testing this variable";
}
echo "Lets test it: $a <br/>";
?>

</body>
</html>

Output

The Global Statement

The global statement comes in handy when you want to access variables that are declared outside
the function. In this if a variable is declared and assigned a value outside a function, and then we
declare a global variable of the same name in the function, then that function can access the
variable that has been declared outside the function.

In the following example we will show how a global variable declared inside a function can
access the variable declared outside the function.

Example:

<html>
<body>
<?php
$a = "Hello how are you";
function abc()
{
global $a;
echo $a;
}
abc();
?>

</body>
</html>

Output

The Static Keyword

The static keyword is used when declaring variables in functions. The purpose of the static
variable is to inform PHP that this variable should not be destroyed when the given function
executes. Instead of destroying that variable, the value of that variable is saved for the next time
needed.
The static variable is used to retain certain variables within the function for the life of the
execution of the script.

Syntax
Static $variable [= initial value];

In the following example we will be using the static variable in the function to see that how
many times a given function has been called.

Example
<html>
<body>

<?php
function func()
{
static $a = 0;
$a++;
echo "This function has executed $a time(s).<br/>";
}

for($i=0; $i<8; $i++)


{
func();
}
?>

</body>
</html>

Output:

You might also like