0% found this document useful (0 votes)
74 views36 pages

PHP Unit 1 Econtent

The document provides an overview of web application development using PHP and MySQL, detailing PHP's characteristics, syntax, and data types. It highlights PHP's performance, open-source nature, and compatibility with various databases, along with examples of basic PHP syntax and operators. Additionally, it explains the structure of PHP code, variable declaration rules, and the different data types supported by PHP.

Uploaded by

varaprasadpgtcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views36 pages

PHP Unit 1 Econtent

The document provides an overview of web application development using PHP and MySQL, detailing PHP's characteristics, syntax, and data types. It highlights PHP's performance, open-source nature, and compatibility with various databases, along with examples of basic PHP syntax and operators. Additionally, it explains the structure of PHP code, variable declaration rules, and the different data types supported by PHP.

Uploaded by

varaprasadpgtcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

D.N.R.

COLLEGE (AUTONOMOUS): BHIMAVARAM


DEPARTMENT OF COMPUTER SCIENCE

Web Applications Development using


PHP& MYSQL
Paper- 7
V SEMESTER
WEB APPLICATIONS DEVELOPMENT USING PHP& MYSQL

UNIT I
INTRODUCTION: PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is the
latest version of PHP, which was released on 28 November. Some important points need to be noticed about
PHP are as followed:
Some facts about PHP:
 PHP has many syntaxes similar to C, Java, and Perl, and has many unique features and specific
functions.
 PHP page is a file with a .php extension can contain a combination of HTML Tags and PHP scripts.
 PHP is Server-side scripting language: Server-side scripting means that the PHP code is processed on
the web server rather than the client machine.
 PHP supports many databases (MySQL and PHP combination is widely used).
 PHP is an open-source scripting language.
 PHP is an object-oriented language.
 PHP is free to download and use.
 PHP is simple and easy to learn language.
CHARACTERISTICS OF PHP(OR)FEATURES OF PHP: PHP is very popular language because of its
simplicity and open source. There are some important features of PHP given below:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 1
1. Performance: PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically
reduced, which results in faster processing speed and better performance.
2. Open Source: PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components are free to
download and use.
3. Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding
with it.
4. Embedded: PHP code can be easily embedded within HTML tags and script.
5. Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A
PHP application developed in one OS can be easily executed in other OS also.
6. Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
7. Error Reporting : PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
8. Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains on its value.
9. Web servers Support: PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.
10. Security: PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
11. Control: Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make changes easily
whenever you want.
12. A Helpful PHP Community: It has a large community of developers who regularly updates
documentation, tutorials, online help, and FAQs. Learning PHP from the communities is one of the
significant benefits.
APPLICATIONS OF PHP: PHP is one of the most widely used language over the web. The following are
the major applications of PHP:
 PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close
them.
 PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data,
return data to the user.
 You add, delete, modify elements within your database through PHP.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 2
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.
PHP SYNTAX
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
Basic PHP Syntax
A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and
some PHP scripting code. PHP statements end with a semicolon (;). Below, we have an example of a simple
PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a
web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Output: My first PHP page


Hello World!
STRUCTURE OF PHP: PHP is an embedded scripting language when used in Web pages. This means that
PHP code is embedded in HTML code. You use HTML tags to enclose the PHP language that you embed in
your HTML file — the same way that you would use other HTML tags. We create and edit Web pages
containing PHP the same way that you create and edit regular HTML pages.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 3
Examples:-

<!DOCTYPE html>
<html>
<body>
<h1>ScmGalaxy</h1>
<?php
echo ‘Hello\n’;
print “World”;
?>
</body>
</html>
2. Commenting
# and // are used to comment out a single line of code, while /* and */ indicate the start and end of a
commented block of code.
1. HTML tags
There are HTML tags for PHP code to indicate the start and end of PHP code in an HTML file. Any one of
the following 4 tags can be used:
1. <?php php-code-here ?>
2. <SCRIPT LANGUAGE="php"> php-code-here </SCRIPT>
3. <? php-code-here ?>
4. <% php-code-here %>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 4
The first and second tags are the ones most recommended and most widely used. Using a tag which is rarely
used may result in a web-server being unable to detect the start and end of the PHP code.
VARIABLES: Variables in a program are used to store some values or data that can be used later in a
program.
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points
to know about variables:
Rules for declaring PHP variable:
o As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It
automatically analyzes the values and makes conversions to its correct datatype.
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
Syntax for creating variable:
$variablename=value;
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
DATA TYPES: PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:
1. Scalar Types (Predefined)
2. Compound Types (User-defined)
3. Special Types
1. Scalar Types (Predefined): It holds only single value. There are 4 scalar data types in PHP.
a. boolean
b. integer
c. float
d. string

Department of Computer Science Web Applications Development using PHP& MYSQL Page 5
a. boolean: Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it returns TRUE
otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is TRUE.
b. integer: Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e.,
numbers without fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$n1 = 10;
$n2 = 10;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 20
c. float: A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with
a fractional or decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;

Department of Computer Science Web Applications Development using PHP& MYSQL Page 6
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
d. string: A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated
differently. To clarify this, see the example below:
Example:
<?php
$college = "DNR";
//both single and double quote statements will treat different
echo "Hello $college";
?>
Output:
Hello DNR
2. Compound Types (User-defined): It can hold multiple values. There are 2 compound data types in
PHP.
a) array
b) object
a) array: An array is a compound data type. It can store multiple values of same data type in a single
variable.

Example:
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Department of Computer Science Web Applications Development using PHP& MYSQL Page 7
Output:
Season are: summer, winter, spring and autumn
b) object: An object is an instance of a class. It’s a central concept in object-oriented programming.
An object has properties. For example, a person object may have the first name, last name, and age
properties.
An object also has behaviours, which are known as methods. For example, a person object can have a method
called getFullName() that returns the full name.
Example:
<?php
class bike
{
function model()
{
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Bike Model: Royal Enfield
3. Special Types: There are 2 special data types in PHP.

a) resource
b) NULL
a) resource: resources: Resources in PHP are not an exact data type. These are basically used to store
references to some function call or to external PHP resources. For example, consider a database call. This
is an external resource. Resource variables hold special handles for files and database connections.
b) NULL: Null is a special data type which can have only one value: NULL. If a variable is created without
a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to
NULL:
Example:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 8
<?php
$nm = NULL;
echo $nm; // this will return no output
// return data type
var_dump($nm);
?>
Output
NULL
PHP OPERATORS: Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values.
For example:
$num=10+20;//+ is the operator and 10,20 are operands
PHP divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional assignment operators

Department of Computer Science Web Applications Development using PHP& MYSQL Page 9
1. Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition, subtraction,
multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

Example:
<?php
$x = 4; // Variable 1
$y = 2; // Variable 2
// Some arithmetic operations on
// these two variables
echo ($x + $y), "\n";
echo($x - $y), "\n";
echo($x * $y), "\n";
echo($x / $y), "\n";
echo($x % $y), "\n";
echo( $x ** $y);
?>
Output:
6
2
8

Department of Computer Science Web Applications Development using PHP& MYSQL Page 10
2
0
16
2. Assignment operators: The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the


left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then $a -= $b Subtraction same as $a = $a - $b


Assign

*= Multiply then $a *= $b Multiplication same as $a = $a * $b


Assign

/= Divide then $a /= $b Find quotient same as $a = $a / $b


Assign
(quotient)

%= Divide then $a %= $b Find remainder same as $a = $a % $b


Assign
(remainder)

Example:
<?php
$x = 10;
echo $x . "<br>"; // Outputs: 10
$x = 20;
$x += 30;
echo $x . "<br>"; // Outputs: 50
$x = 50;
$x -= 20;
echo $x . "<br>"; // Outputs: 30
$x = 5;
$x *= 25;
echo $x . "<br>"; // Outputs: 125
$x = 50;
Department of Computer Science Web Applications Development using PHP& MYSQL Page 11
$x /= 10;
echo $x . "<br>"; // Outputs: 5
$x = 100;
$x %= 15;
echo $x . "<br>"; // Outputs: 10
OUTPUT:
10
50
30
125
5
10
3. Comparison operators: These operators are used to compare two elements and output the result in
boolean form.

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === Returns true if $x is equal to $y, and they are of the same type
$y

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same
type

> Greater than $x > $y Returns true if $x is greater than $y

Department of Computer Science Web Applications Development using PHP& MYSQL Page 12
< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

<=> Spaceship $x <=> Returns an integer less than, equal to, or greater than zero,
$y depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.

4. Increment/Decrement operators: The increment and decrement operators are used to increase and
decrease the value of a variable.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

5. Logical operators: The logical operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

Department of Computer Science Web Applications Development using PHP& MYSQL Page 13
or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

6. String operators: The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign the


Assignment concatenated string to $a, e.g. $a = $a . $b

7. Array operators: The array operators are used in case of array. Basically, these operators are used to
compare the values of arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

Department of Computer Science Web Applications Development using PHP& MYSQL Page 14
== Equality $x == $y Returns true if $x and $y have the same key/value pairs

=== Identity $x === Returns true if $x and $y have the same key/value pairs in the
$y same order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non- $x !== $y Returns true if $x is not identical to $y


identity

8. Conditional assignment operators: The PHP conditional assignment operators are used to set a value
depending on conditions:

Operator Name Example Result

?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.


The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE

FLOW CONTROL FUNCTIONS IN PHP


Flow Control Functions in PHP: PHP supports a number of traditional programming constructs for
controlling the flow of execution of a program. Control statements are conditional statements that execute a
block of statements if the condition is correct. The statement inside the conditional block will not execute
until the condition is satisfied.
CONDITIONAL STATEMENTS: PHP provides us with five conditional statements:
1. if statement
2. if…else statement
3. if…elseif…else statement

Department of Computer Science Web Applications Development using PHP& MYSQL Page 15
4. nested if
5. switch statement
1. if statement: If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.

Syntax:
if(condition)
{
//code to be executed
}
Flowchart:

Example
<?php
$num=12;
if($num<100)
{
echo "$num is less than 100";
}
?>
Output: 12 is less than 100
2. if…else statement: PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes one block of code if the specified
condition is true and another block of code if the condition is false.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 16
Syntax:
if(condition)
{
//code to be executed if true
}
else
{
//code to be executed if false
}
Flowchart

Example:
<?php
$num=12;
if($num%2==0)
{
echo "$num is even number";
}
else
{
echo "$num is odd number";
}
?>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 17
Output:
12 is even number

3. If…else if…else statement: The PHP if-else-if is a special statement used to combine multiple if else
statements. So, we can check multiple conditions using this statement.
Syntax:
if (condition1)
{
//code to be executed if condition1 is true
}
elseif (condition2)
{
//code to be executed if condition2 is true
}
elseif (condition3)
{
//code to be executed if condition3 is true
....
}
else
{
//code to be executed if all given conditions are false
}
Flowchart:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 18
Example
<?php
$marks=69;
if ($marks<33)
{
echo "fail";
}
else if ($marks>=34 && $marks<50)
{
echo "D grade";
}
else if ($marks>=50 && $marks<65)
{
echo "C grade";
}
else if ($marks>=65 && $marks<80)
{
echo "B grade";
}
else if ($marks>=80 && $marks<90)
{
echo "A grade";
}
else if ($marks>=90 && $marks<100)
{
echo "A+ grade";
}
else
{
echo "Invalid input";
}
?>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 19
Output:
B Grade
4. Nested if: The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
}
Flowchart

Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{

Department of Computer Science Web Applications Development using PHP& MYSQL Page 20
if ($age >= 18)
{
echo "Eligible to give vote";
}
else
{
echo "Not eligible to give vote";
}
}
?>
Output:
Eligible to give vote
5. switch statement: The “switch” performs in various cases i.e., it has various cases to which it matches
the condition and appropriately executes a particular case block. It first evaluates an expression and then
compares with the values of each case. If a case matches then the same case is executed. To use switch, we
need to get familiar with two different keywords namely, break and default.
1. The break statement is used to stop the automatic control flow into the next cases and exit from the
switch case.
2. The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}

Department of Computer Science Web Applications Development using PHP& MYSQL Page 21
Flowchart:

Example:
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":

Department of Computer Science Web Applications Development using PHP& MYSQL Page 22
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
LOOPING STATEMENTS: Like any other language, loop in PHP is used to execute a statement or a
block of statements, multiple times until and unless a specific condition is met. This helps the user to save
both time and effort of writing the same code multiple times.
PHP supports four types of looping techniques;
1. for loop
2. while loop
3. do-while loop
4. foreach loop
1. for loop: PHP for loop can be used to execute same block of statements for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for loop is used
when you already know how many times you want to execute a block of code.
Syntax:
for (initialization expression; test condition; update expression)
{
// code to be executed
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then
check whether this variable is less than or greater than counter value. If statement is true, then loop body is
executed and loop variable gets updated . Steps are repeated till exit condition comes.
 Initialization Expression: In this expression we have to initialize the loop counter to some value. for
example: $num = 1;
 Test Expression: In this expression we have to test the condition. If the condition evaluates to true then
we will execute the body of loop and go to update expression otherwise we will exit from the for loop.
For example: $num <= 10;
 Update Expression: After executing loop body this expression increments/decrements the loop variable
by some value. for example: $num += 2;

Department of Computer Science Web Applications Development using PHP& MYSQL Page 23
Flowchat

Example:
<?php
// code to illustrate for loop
for ($num = 1; $num <= 5; $num += 1)
{
echo "$num \n";
}
?>
Output: 1
2
3
4
5
2. while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at
the start of the loop and if it is true then it enters the loop and executes the block of statements until
particular condition is false.
Department of Computer Science Web Applications Development using PHP& MYSQL Page 24
Syntax:
while (if the condition is true)
{
// code is executed
Inc/dec;
}
Flowchart:

Example:
<?php
$n=1;
while($n<=5)
{
echo "$n<br/>";
$n++;
}
?>

Output:
1
2
3
4
5
Department of Computer Science Web Applications Development using PHP& MYSQL Page 25
Example: WRITE PHP PROGRAM TO DISPLAY FIBONACCI SERIES
<!DOCTYPE html>
<html>
<body>
<?php
$num = 0;
$n1 = 0;
$n2 = 1;
echo "<h3>Fibonacci series for first 12 numbers: </h3>";
echo "\n";
echo $n1.' '.$n2.' ';
while ($num < 10 )
{
$n3 = $n2 + $n1;
echo $n3.' ';
$n1 = $n2;
$n2 = $n3;
$num = $num + 1;
}
?>
</body>
</html>

Output:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 26
Example: WRITE PHP PROGRAM TO CHECK THE GIVEN NUMBER IS PALINDROME OR NOT

<!DOCTYPE html>
<html>
<body>
<?php
$num = 121;
$sum = 0;
$n =$num;
while(floor($num))
{
$r = $num%10;
$sum = $sum * 10 + $r;
$num = $num/10;
}
if($n==$sum)
{
echo "$n is a Palindrome number.";
}
else
{
echo "$n is not a Palindrome number.";
}
?>
</body>
</html>
Output: 121 is a Palindrome number.
3. do-while loop: This is an exit control loop which means that it first enters the loop, executes the
statements, and then checks the condition. Therefore, a statement is executed at least once on using the
do…while loop. After executing once, the program is executed as long as the condition holds true.
Syntax:
do
{

Department of Computer Science Web Applications Development using PHP& MYSQL Page 27
//code to be executed
}while(condition);
Flowchart:

Example
<?php
$n=1;
do
{
echo "$n<br/>";
$n++;
}while($n<=5);
?>
Output:
1
2
3
4
5

Department of Computer Science Web Applications Development using PHP& MYSQL Page 28
WORKING WITH FUNCTIONS
Function: A function is a block of code written in a program to perform some specific task.. It can take
input as argument list and return value. There are thousands of built-in functions in PHP.
PHP provides us with two major types of functions:
 Built-in functions : PHP provides us with huge collection of built-in library functions. These functions
are already coded and stored in form of functions. To use those we just need to call them as per our
requirement like, var_dump, fopen(), print_r(), gettype() and so on.
 User Defined Functions : Apart from the built-in functions, PHP allows us to create our own
customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply calling it.
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of
function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of
the application because every logic is divided in the form of functions.
Creating a Function
While creating a user defined function we need to keep few things in mind:
1. Any name ending with an open and closed parenthesis is a function.
2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or underscore.
5. A function name is not case-sensitive.
Syntax:
function function_name()
{
executable code;
}
PHP Functions Example:
<?php
function sayHello()
{

Department of Computer Science Web Applications Development using PHP& MYSQL Page 29
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
PHP FUNCTION ARGUMENTS: We can pass the information in PHP function through arguments which
is separated by comma. PHP supports 4 types of function arguments
1. Call by Value (default),
2. Call by Reference
3. Default argument values
4. Variable-length argument list.
1. Call by Value: Call by value means passing the value directly to a function. The called function uses the
value in a local variable; any changes to it do not affect the source variable. Let's see the example to pass two
argument in PHP function.
<?php
function sayHello($name,$age)
{
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old
2. Call By Reference: Value passed to the function doesn't modify the actual value by default (call by
value). But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to use
ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 30
Example:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference
3. Default Argument Value: We can specify a default argument value in function. While calling PHP
function if you don't specify any argument, it will take the default argument.
Let's see a simple example of using default argument value in PHP function.
Example:
<?php
function sayHello($name="Sonoo")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
4. Returning Value
Let's see an example of PHP function that returns value.
Example:
<?php

Department of Computer Science Web Applications Development using PHP& MYSQL Page 31
function cube($n)
{
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
PHP PARAMETERIZED FUNCTION: PHP Parameterized functions are the functions with parameters.
You can pass any number of parameters inside a function. These passed parameters act as variables inside
your function.They are specified inside the parentheses, after the function name.The output depends upon the
dynamic values passed as the parameters into the function.
PHP Parameterized Example 1:
Addition and Subtraction
In this example, we have passed two parameters $x and $y inside two functions add() and sub().
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
//Adding two numbers
function add($x, $y)
{
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
//Subtracting two numbers
function sub($x, $y)
{
$diff = $x - $y;

Department of Computer Science Web Applications Development using PHP& MYSQL Page 32
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</html>
Output:

TYPES OF VARIABLES: In PHP, variables can be declared anywhere in the script. The scope of a variable
is the part of the script where the variable can be referenced/used.
PHP has three types of variable scopes:
1. Local variable
2. Global variable
3. Static variable
1. Local variable: The variables that are declared within a function are called local variables for that
function. These local variables have their scope only in that particular function in which they are declared.
This means that these variables cannot be accessed outside the function, as they have local scope.
Example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
Local variable declared inside the function is: 45
Department of Computer Science Web Applications Development using PHP& MYSQL Page 33
2. Global variable: The global variables are the variables that are declared outside the function. These
variables can be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the
function without any keyword. Therefore there is no need to use any keyword to access a global variable
outside the function.
Let's understand the global variables with the help of an example:
Example:
<?php
$name = "DNR"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Variable inside the function: DNR
Variable outside the function: DNR
3. Static variable: Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use
the static keyword when you first declare the variable:
Example
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();

Department of Computer Science Web Applications Development using PHP& MYSQL Page 34
myTest();
myTest();
?>
Output: 0
1
2

Department of Computer Science Web Applications Development using PHP& MYSQL Page 35

You might also like