0% found this document useful (0 votes)
133 views70 pages

PHP & MySQL Web Development Syllabus

The document contains the syllabus for a course on Web Applications Development Using PHP & MYSQL. The syllabus is divided into 5 units that cover topics like the building blocks of PHP including variables, data types, operators, functions, arrays, objects, strings, dates, forms, cookies, sessions, files, directories, images, and interacting with MySQL databases. It also includes a practical lab syllabus with 20 exercises on developing PHP applications and connecting to MySQL databases to perform operations like user registration, form handling, table manipulation, and dynamic website creation. References and resources for the course are provided at the end.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views70 pages

PHP & MySQL Web Development Syllabus

The document contains the syllabus for a course on Web Applications Development Using PHP & MYSQL. The syllabus is divided into 5 units that cover topics like the building blocks of PHP including variables, data types, operators, functions, arrays, objects, strings, dates, forms, cookies, sessions, files, directories, images, and interacting with MySQL databases. It also includes a practical lab syllabus with 20 exercises on developing PHP applications and connecting to MySQL databases to perform operations like user registration, form handling, table manipulation, and dynamic website creation. References and resources for the course are provided at the end.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

ADITHYA DEGREE & PG

COLLEGE
ADITHYA NAGAR, SPSR NELLORE

DEPARTMENT OF COMPUTER SCIENCE

B.Sc Computer Science / Information Technology

Final Year : Sem-V

(COURCE CODE – 7A)

Web Applications Development Using


PHP & MYSQL
Prepared By
V.SRINIVASULU M.Sc.,

Syllabus
Name:

Group: Roll No:


OM SAIRAM 2

Web Applications Development Using PHP & MYSQL


Syllabus
Unit-1: (10 hours)
The Building blocks of PHP: Variables, Data Types, Operators and Expressions, Constants.
Flow Control Functions in PHP: Switching Flow, Loops, Code Blocks and Browser Output.
Working with Functions: What is function?, Calling functions, Defining Functions, Returning
the values from User-Defined Functions, Variable Scope, Saving state between Function
calls with the static statement, more about arguments.
Unit-2: (10 hours)
Working with Arrays: What are Arrays? Creating Arrays, Some Array-Related Functions.
Working with Objects: Creating Objects, Object Instance Working with Strings, Dates and
Time: Formatting strings with PHP, Investigating Strings with PHP, Manipulating Strings
with PHP, Using Date and Time Functions in PHP.
Unit-3: (10 hours)
Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays,
Combining HTML and PHP code on a single Page, Using Hidden Fields to save state,
Redirecting the user, Sending Mail on Form Submission, and Working with File Uploads.
Working with Cookies and User Sessions: Introducing Cookies, Setting a Cookie with PHP,
Session Function Overview, Starting a Session, Working with session variables, passing
session IDs in the Query String, Destroying Sessions and Unsetting Variables, Using
Sessions in an Environment with Registered Users.
Unit-4: (10 hours)
Working with Files and Directories: Including Files with inclue(), Validating Files, Creating
and Deleting Files, Opening a File for Writing, Reading or Appending, Reading from Files,
Writing or Appending to a File, Working with Directories, Open Pipes to and from Process
Using popen(), Running Commands with exec(), Running Commands with system() or
passthru().
Working with Images: Understanding the Image-Creation Process, Necessary Modifications
to PHP, Drawing a New Image, Getting Fancy with Pie Charts, Modifying Existing Images,
Image Creation from User Input.
Unit-5: (10 hours)
Interacting with MySQL using PHP: MySQL Versus MySQLi Functions, Connecting to MySQL
with PHP, Working with MySQL Data. Creating an Online Address Book: Planning and Creating
Database Tables, Creating Menu, Creating Record Addition Mechanism, Viewing Records,
Creating the Record Deletion Mechanism, Adding Sub-entities to a Record.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 3

References
1. Julie C. Meloni, SAMS Teach yourself PHP MySQL and Apache, Pearson
Education (2007).
2.Steven Holzner , PHP: The Complete Reference, McGraw-Hill
3. Robin Nixon, Learning PHP, MySQL, JavaScript, CSS & HTML5, Third
Edition O'reilly, 2014
4. Xue Bai Michael Ekedahl, The web warrior guide to Web Programming,
Thomson (2006).
5. Web resources:
e. http://www.codecademy.com/tracks/php
f. http://www.w3schools.com/PHP
g. http://www.tutorialpoint.com
6. Other web sources suggested by the teacher concerned and the college
librarian including reading material.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 4

Practical (Laboratory) Syllabus: (30 hrs.)


1. Write a PHP program to Display “Hello”
2. Write a PHP Program to display the today’s date.
3. Write a PHP program to display Fibonacci series.
4. Write a PHP Program to read the employee details.
5. Write a PHP program to prepare the student marks list.
6. Write a PHP program to generate the multiplication of two matrices.
7. Create student registration form using text box, check box, radio button,
select, submit button. And display user inserted value in new PHP page.
8. Create Website Registration Form using text box, check box, radio button,
select, submit button. And display user inserted value in new PHP page.
9. Write PHP script to demonstrate passing variables with cookies.
10. Write a program to keep track of how many times a visitor has loaded the page.
11. Write a PHP application to add new Rows in a Table.
12. Write a PHP application to modify the Rows in a Table.
13. Write a PHP application to delete the Rows from a Table.
14. Write a PHP application to fetch the Rows in a Table.
15. Develop an PHP application to implement the following Operations
i. Registration of Users.
ii. Insert the details of the Users.
iii. Modify the Details.
iv. Transaction Maintenance.
a) No of times Logged in
b) Time Spent on each login.
c) Restrict the user for three trials only.
d) Delete the user if he spent more than 100 Hrs of transaction.
16. Write a PHP script to connect MySQL server from your website.
17. Write a program to read customer information like cust-no, cust-name, item-
purchased, and mob-no, from customer table and display all these information
in table format on output screen.
18. Write a program to edit name of customer to “Kiran” with cust-no =1, and to
delete record with cust-no=3.
19. Write a program to read employee information like emp-no, emp-name,
designation and salary from EMP table and display all this information using
table format in your website.
20. Create a dynamic web site using PHP and MySQL.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 5

Unit-1
The Building blocks of PHP
Variables: A variable is a special container that we can define, which then “holds”
a value, such as a number, string, object, array, or a Boolean. Variables are
fundamental to programming. Without variables, we would be forced to write
hard-code each specific value used in our scripts. For example the following hard-
coded statement adds two numbers together and prints the result, which solves a
simple mathematics problem:
echo (2 + 4);
However, this snippet of code is useful only for person, who specifically want to
know the sum of 2 and 4. Similarly, in order to find the sum of two other numbers
say 3 and 5, we have to write one more instruction. That means, each time the
values get changed, we have to write separate instruction. However, this approach
to programming is clearly meaningless, and this is where variables come into play.
Here are the most important things to know about variables in PHP.
 A variable must start with a dollar ($) sign, followed by the variable name.
 It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
 A PHP variable name cannot contain spaces.
 PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 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.
 Variables in PHP do not have built-in types. That is, a variable does not know in
advance whether it will be used to store a number or a string of characters.
 Variables used before they are assigned will have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
 After declaring a variable, it can be reused throughout the code.
 Better to use short, meaningful and descriptive variable names.
 Declaration must be terminated with semi-colon.
 PHP variables are Perl-like.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 6

Valid Examples:
$fee;
$a_longish_variable_name;
$subject1;
$stud_name;
Invalid Examples:
Invalid Example Reason
Total Must start with $ symbol.
$total Marks Blank spaces are not allowd.
$2x Variable name must not start with digit.
$a+b-(c+d/2) Special symbols are not allowed.

PHP Global Variables – Superglobals: Some predefined variables in PHP are "superglobals",
which means that they are always accessible, regardless of scope - and you can access them
from any function, class or file without having to do anything special.
The PHP superglobal variables are:
 $_GET contains any variables provided to a script through the GET method.
 $_POST contains any variables provided to a script through the POST method.
 $_COOKIE contains any variables provided to a script through a cookie.
 $_FILES contains any variables provided to a script through file uploads.
 $_SERVER contains information such as headers, file paths, and script
locations.
 $_ENV contains any variables provided to a script as part of the server
environment.
 $_REQUEST contains any variables provided to a script via GET, POST, or
COOKIE input mechanisms.
 $_SESSION contains any variables that are currently registered in a session.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 7

Data Types: A data type specifies the amount of memory that allocates to a value
associated with it. A type also determines the operations that you can perform on it. 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:

PHP Boolean: Booleans are the simplest data type works like electrical 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.
PHP 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:
 An integer can be either positive or negative.
 An integer must not contain decimal point.
 Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 8

 The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 that
is, -231 to 231.
Example:
<?php   
    $dec1 = 34;  
    $oct1 = 0243;  
    $hexa1 = 0x45;  
    echo "Decimal number: " .$dec1. "</br>";  
    echo "Octal number: " .$oct1. "</br>";  
    echo "HexaDecimal number: " .$hexa1. "</br>";  
?>  
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP 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;  
    $n2 = 54.472;  
    $sum = $n1 + $n2;  
    echo "Addition of floating numbers: " .$sum;  
?>  
Output:
Addition of floating numbers: 73.812
PHP 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. The following example illustrates this
clearly.
Example:
<?php   
    $name = "Sai Dhanush";  
    //both single and double quote statements will be treated as different  
    echo "Hello $name";  
    echo "</br>";  

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 9

    echo 'Hello $name';  
?>  

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 10

Output:
Hello Sai Dhanush
Hello $name
PHP Array: An array is a compound data type. It can store multiple values of same data
type in a single variable.
Example:
<?php   
    $bikes = array ("Royal Enfield", "Yamaha", "Hero");  
    var_dump($bikes);   //the var_dump() function returns the datatype and values  
    echo "</br>";  
    echo "Array Element1: $bikes[0] </br>";  
    echo "Array Element2: $bikes[1] </br>";  
    echo "Array Element3: $bikes[2] </br>";  
?>  
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "Hero" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: Hero
PHP object: Objects are the instances of user-defined classes that can store both values
and functions. They must be explicitly declared.
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
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 11

PHP Resource: Resources are not the exact data type in PHP. Basically, these are used to
store some function calls or references to external PHP resources. For example - a
database call. It is an external resource.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it
in capital letters as it is case sensitive. The special type of data type NULL defined a
variable with no value.
Example:
<?php   
$nl = NULL;  
echo $nl;   //it will not give any output  
?>  
Output:
Operators and Expressions
Operator: Generally operator is a special symbol or keyword that is used to perform
certain operation. For example in an expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. PHP language supports following type of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators: There are following arithmetic operators supported by PHP language
− Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value by one A++ will give 11

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 12

-- Decrement operator, decreases integer value by A-- will give 9


one
Example:
<html>
<head>
<title>Arithmetical Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addtion Operation Result: $c <br/>";
$c = $a - $b;
echo "Substraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>
</body>
</html>
Output:
Addtion Operation Result: 62
Substraction Operation Result: 22
Multiplication Operation Result: 840
Division Operation Result: 2.1
Modulus Operation Result: 2
Increment Operation Result: 42

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 13

Decrement Operation Result: 43

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 14

Comparison Operators: There are following comparison operators supported by PHP


language. Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example

== Checks if the value of two operands are equal or not, if (A == B) is not


yes then condition becomes true. true.

!= Checks if the value of two operands are equal or not, if (A != B) is true.


values are not equal then condition becomes true.

> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes
true.

< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition becomes
true.

>= Checks if the value of left operand is greater than or (A >= B) is not
equal to the value of right operand, if yes then true.
condition becomes true.

<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.
<html>
<head>
<title>Comparison Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ) {
echo "TEST1 : a is equal to b<br/>";
}else {
echo "TEST1 : a is not equal to b<br/>";
}
if( $a > $b ) {

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 15

echo "TEST2 : a is greater than b<br/>";


}else {
echo "TEST2 : a is not greater than b<br/>";
}
if( $a < $b ) {
echo "TEST3 : a is less than b<br/>";
}else {
echo "TEST3 : a is not less than b<br/>";
}
if( $a != $b ) {
echo "TEST4 : a is not equal to b<br/>";
}else {
echo "TEST4 : a is equal to b<br/>";
}
if( $a >= $b ) {
echo "TEST5 : a is either greater than or equal to b<br/>";
}else {
echo "TEST5 : a is neither greater than nor equal to b<br/>";
}
if( $a <= $b ) {
echo "TEST6 : a is either less than or equal to b<br/>";
}else {
echo "TEST6 : a is neither less than nor equal to b<br/>";
}
?>
</body>
</html>
Output:
TEST1 : a is not equal to b
TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either greater than or equal to b
TEST6 : a is neither less than nor equal to b

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 16

Logical Operators: There are following logical operators supported by PHP language.
Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example

and Called Logical AND operator. If both the operands are true (A and B) is
then condition becomes true. true.

or Called Logical OR Operator. If any of the two operands are (A or B) is


non zero then condition becomes true. true.

&& Called Logical AND operator. If both the operands are non (A && B) is
zero then condition becomes true. true.

|| Called Logical OR Operator. If any of the two operands are (A || B) is


non zero then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical !(A && B) is
state of its operand. If a condition is true then Logical false.
NOT operator will make false.
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ) {
echo "TEST1 : Both a and b are true<br/>";
}else{
echo "TEST1 : Either a or b is false<br/>";
}
if( $a and $b ) {
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
}
if( $a || $b ) {

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 17

echo "TEST3 : Either a or b is true<br/>";


}else{
echo "TEST3 : Both a and b are false<br/>";
}
if( $a or $b ) {
echo "TEST4 : Either a or b is true<br/>";
}else {
echo "TEST4 : Both a and b are false<br/>";
}
$a = 10;
$b = 20;
if( $a ) {
echo "TEST5 : a is true <br/>";
}else {
echo "TEST5 : a is false<br/>";
}
if( $b ) {
echo "TEST6 : b is true <br/>";
}else {
echo "TEST6 : b is false<br/>";
}
if( !$a ) {
echo "TEST7 : a is true <br/>";
}else {
echo "TEST7 : a is false<br/>";
}
if( !$b ) {
echo "TEST8 : b is true <br/>";
}else {
echo "TEST8 : b is false<br/>";
}
?>
</body>
</html>
Output:

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 18

TEST1 : Either a or b is false


TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false

Assignment Operators: There are following assignment operators supported by PHP


language.
Operator Description Example

= Simple assignment operator, Assigns values from C = A + B will assign


right side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right C += A is equivalent


operand to the left operand and assign the result to to C = C + A
left operand

-= Subtract AND assignment operator, It subtracts C -= A is equivalent


right operand from the left operand and assign the to C = C - A
result to left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent


right operand with the left operand and assign the to C = C * A
result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent


operand with the right operand and assign the result to C = C / A
to left operand

%= Modulus AND assignment operator, It takes modulus C %= A is equivalent


using two operands and assign the result to left to C = C % A
operand
Example:
<html>
<head>
<title>Assignment Operators</title>

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 19

</head>
<body>

<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addtion Operation Result: $c <br/>";
$c += $a;
echo "Add AND Assigment Operation Result: $c <br/>";
$c -= $a;
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a;
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a;
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a;
echo "Modulus AND Assignment Operation Result: $c <br/>";
?>
</body>
</html>
Output:
Addtion Operation Result: 62
Add AND Assigment Operation Result: 104
Subtract AND Assignment Operation Result: 62
Multiply AND Assignment Operation Result: 2604
Division AND Assignment Operation Result: 62
Modulus AND Assignment Operation Result: 20
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression
for a true or false value and then execute one of the two given statements depending upon
the result of the evaluation. The conditional operator has this syntax −
Operator Description Example

?: Conditional If Condition is true ? Then value X :


Expression Otherwise value Y

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 20

<html>
<head>
<title>Conditional Operator</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>
Output:
TEST1 : Value of result is 20
TEST2 : Value of result is 10
Operators Categories:
All the operators can be categorised into following categories −
 Unary prefix operators, which precede a single operand.
 Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
 The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
 Assignment operators, which assign a value to a variable.
Precedence of PHP Operators
Operator precedence determines the order of evaluation of operators in an expression.
This affects how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the addition
operator.
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds 7.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 21

Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 22

Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left

Expressions
Introduction: Almost everything in a PHP script is an expression. Anything that
evaluates/has a value is an expression. In a typical assignment statement ($x=100), a literal
value, a function or operands processed by operators is an expression, anything that
appears to the right of assignment operator (=).
Syntax:
$x=100; //100 is an expression
$a=$b+$c; //$b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
Expression with ++ and -- operators
These operators are called increment and decrement operators respectively. These are
unary operators, needing just one operand and can be used in prefix or postfix manner,
although with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 whereas -- operator
decrements by 1. However, when used in assignment expression, prefix makes
incremnt/decrement first and then followed by assignment. In case of postfix, assignment
is done before increment/decrement.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 23

Example-1
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
Output
This produces following result
x = 11 y = 10
Example-2
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
Output
This produces following result
x = 11 y = 11
Expression with Ternary conditional operator:
Ternary operator has three operands. First one is a logical expression. If it is TRUE,
second operand expression is evaluated otherwise third one is evaluated.
Example
<?php
$marks=60;
$result= $marks<50 ? "Fail" : "Pass";
echo $result;
?>
Output
Following result will be displayed
Pass

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 24

PHP - Constants Types


A constant is a name or an identifier given to constant value which cannot change during the
execution of the script. By default, a constant is case-sensitive. By convention, constant
identifiers are always uppercase. A constant name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores. Onece a constant is defined, it
can not be changed or undefined.
To define a constant we have to use define( ) function and to retrieve the value of a
constant, we have to simply specifying its name. Unlike with variables, we do not need to
have a constant with a $. We can also use the function constant( ) to read a constant's
value if we wish to obtain the constant's name dynamically.
constant() function: As indicated by the name, this function will return the value of the
constant. This is useful when we want to retrieve value of a constant, but we do not know its
name.
Example:
<?php
define("MINSIZE", 50);

echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Note: Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables:
 There is no need to write a dollar sign ($) before a constant, where as in Variable
one has to write a dollar sign.
 Constants cannot be defined by simple assignment, they may only be defined using
the define() function.
 Constants may be defined and accessed anywhere without regard to variable
scoping rules.
 Once the Constants have been set, may not be redefined or undefined.
Valid Examples:
// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");
define("__THREE__", "third value");

Invalid Example:

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 25

define("2TWO", "second thing");


PHP Magic/Predefined Constants:
PHP provides a large number of predefined constants to any script which it runs.
There are five magical constants that change depending on where they are used. For
example, the value of __LINE__ depends on the line that it's used on in our script. These
special constants are case-insensitive and are as follows −
A few "magical" PHP constants are given below −
Sr.No Name & Description

1 __LINE__
The current line number of the file.

2 __FILE__
The full path and filename of the file. If used inside an include,the name of the
included file is returned. Since PHP 4.0.2, __FILE__ always contains an
absolute path whereas in older versions it contained relative path under some
circumstances.

3 __FUNCTION__
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
function name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.

4 __CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
class name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.

5 __METHOD__
The class method name. (Added in PHP 5.0.0) The method name is returned as it
was declared (case-sensitive).

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 26

Flow Control Functions in PHP


Switching flow: Most scripts evaluate conditions and change their behavior accordingly. The
capability to make decisions makes our PHP pages dynamic, able to change their output
according to circumstances. Like most programming languages, PHP allows us to do this with
an If statement.
In PHP we have the following conditional statements:
a) if statement - executes some code if one condition is true
b) if...else statement - executes some code if a condition is true and another code if
that condition is false
c) if...elseif...else statement - executes different codes for more than two conditions
d) switch statement - selects one of many blocks of code to be executed
a)The if Statement
An ‘if’ statement is a way of controlling the execution of a statement that follows it (that
is, a single statement or a block of code inside braces). The if statement evaluates an
expression between parentheses. If this expression results in a true value, the statement is
executed. Otherwise, the statement is skipped entirely. This enables scripts to make
decisions based on any number of factors:
Syntax:
if ( expression )
{
// code to execute if the expression evaluates to true
}
Example:
<html>
<head>
<title>Simple If</title>
</head>
<body>
?php
$mood = "happy";
if ( $mood == "happy" )
{
print "Hooray, I'm in a good mood";
}
?>
</body>

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 27

</html>
b) The If...Else Statement:If we want to execute some code if a condition is true and
another code if a condition is false, we use the if....else statement.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example

The following example will output "Have a nice weekend!" if the current day is Saturday,
Otherwise, it will output "Have a nice day!":
<html>
<body>
<?php
$d = date("D");
if ($d == "Sat")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
Output:
Have a nice weekend!

c) The ElseIf Statement: If we want to execute some code if one of the several
conditions are true use the elseif statement.
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 28

code to be executed if condition is false;


Example
The following example will output "Have a nice weekend!" if the current day is Saturday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice
day!" −
<html>
<body>
<?php
$d = date("D");
if ($d == "Sat")
echo "Have a nice weekend!";
elseif ($d == "Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
Output:
Have a nice Weekend!

d) The Switch Statement

If we want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;

case label2:
code to be executed if expression = label2;

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 29

break;

case label-n:
code to be executed if expression = label-n;
break;

default:
default code to be executed if miss match occurs;
}
Example

The switch statement works in an unusual way as in C. First it evaluates given expression


then seeks a lable to match the resulting value. If a matching value is found then the code
associated with the matching label will be executed or if none of the lable matches then
statement will execute any specified default code.

<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 30

case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Sorry... Invalid Day! ";
}
?>
</body>
</html>
Output:
Today is Monday

Iterative Control Structures


Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

a) for − loops through a block of code a specified number of times.


b) while − loops through a block of code if and as long as a specified condition is true.
c) do...while − loops through a block of code once, and then repeats the loop as long
as a special condition is true.
d) foreach − loops through a block of code for each element in an array.
a) The for loop statement: The for statement is used when you know how many times you
want to execute a statement or a block of statements.

Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to name it
$i.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 31

Example

The following example makes five iterations and changes the assigned value of two variables
on each pass of the loop −

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 32

<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
</body>
</html>
Output:
At the end of the loop a = 50 and b = 25
b) The while loop statement: The while statement will execute a block of code if and as
long as a test expression is true. If the test expression is true then the code block will
be executed. After the code has executed the test expression will again be evaluated and
the loop will continue until the test expression is found to be false.

Syntax
while (condition)
{
code to be executed;
}
Example: This example decrements a variable value on each iteration of the loop and the
counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 33

while( $i < 10)


{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
Output:

Loop stopped at i = 10 and num = 40

c) The do...while loop statement: The do...while statement will execute a block of
code at least once - it then will repeat the loop as long as a condition is true.
Syntax
do
{
code to be executed;
}while (condition);
Example: The following example will increment the value of i at least once, and it will
continue incrementing the variable i as long as it has a value of less than 10 −
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 34

</html>
Output:

Loop stopped at i = 10
d) The foreach loop statement: The foreach statement is used to loop through arrays.
For each pass the value of the current array element is assigned to $value and the
array pointer is moved by one and in the next pass next element will be processed.

Syntax
foreach (array as value)
{
code to be executed;
}
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce the following result −

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 35

Unconditional Control Structures

a) The break Statement: The PHP break keyword is used to terminate the execution


of a loop prematurely. The break statement is situated inside the statement block. It
gives you full control and whenever you want to exit from the loop you can come out.
After coming out of a loop immediate statement to the loop will be executed.

Example:
<html>
<body>
<?php
$i = 0;
while( $i < 10) {
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Output:
Loop stopped at i = 3

b) The continue Statement: The PHP continue keyword is used to halt the current


iteration of a loop but it does not terminate the loop. Just like the break statement
the continue statement is situated inside the statement block containing the code
that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass
starts.

Example: In the following example loop prints the value of array but for which
condition becomes true it just skip the code and next value is printed.
<html>
<body>
<?php

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 36

$array = array( 1, 2, 3, 4, 5);


foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
Output:

Value is 1
Value is 2
Value is 4
Value is 5

Code Blocks and Browser Output

Description

A code block is a list of statements grouped as one unit.

Syntax

In PHP we use {} to wrap code blocks and notify the compiler by saying, "hey this is a group
of statements."

Example
<html>
<head>
<title>Listing 5.13</title>
</head>
<body>
<?php
$display_prices = true;
if ( $display_prices )

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 37

{
print "<table border=\"1\">";
print "<tr><td colspan=\"3\">";
print "today's prices in dollars";
print "</td></tr>";
print "<tr><td>14</td><td>32</td><td>71</td></tr>";
print "</table>";
}
?>
</body>
</html>
If the value of $display_prices is set to true in line 2, the table is printed. For the
sake of readability, we split the output into multiple echo() statements, and once
again use the backslash to escape any quotation marks used in the HTML output.

Put these lines into a text file called testmultiecho.php and place this file in web
server’s document root. When we access this script through our web browser, it
should look like as follows.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 38

There’s nothing wrong with the way this is coded, but you can save yourself some
typing by simply slipping back into HTML mode within the code block as follows.

<?php
$display_prices = true;
if ($display_prices)
{ ?>
<table border=”1”>
<tr>
<td colspan=”3”> today’s prices in dollars </td>
</tr>
<tr>
<td>$14.00</td>
<td>$32.00</td>
<td>$71.00</td>
</tr>
</table>
<?php
}
?>
The important thing to note here is that the shift to HTML mode occurs only if
the condition of the if statement is fulfilled. This can save you the bother of
escaping quotation marks and wrapping our output in echo() statements. This
approach might, however, affect the readability of the code in the long run,
espe- cially if the script grows larger.

Working with Functions


What is function?
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns
a value. PHP provides us with two major types of functions: 
a) 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.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 39

b) 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.
In fact we hardly need to create our own PHP function because there are already more than
1000 of built-in library functions created for different area and we just need to call them
according to our requirement.

Advantage of PHP Functions

 Functions reduces the repetition of code within a program 


 Functions makes the code much easier to maintain

 Functions makes it easier to eliminate the errors

 Functions can be reused in other application

Defining and Calling a PHP Function (User Defined Function): It is very easy to create
our own PHP function. Suppose if we want to create a PHP function which will simply write a
simple message on our browser when we will call it, the following example creates a function
called writeMessage() and then calls it just after creating it. In PHP, while creating a
function its name should start with keyword function and all the PHP code should be put
inside { and } braces as shown in the following example.
Example:
<html>
<head>
<title> Writing PHP Function </title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo " Education Is The Only Weapon That Can Change The Entire World!";
}
/* Calling a PHP Function */
writeMessage();
?>

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 40

</body>
</html>
Output:
Education Is The Only Weapon That Can Change The Entire World!

Returning value from User-Defined Functions: A function can return a value using
the ‘return’ statement in conjunction with a value or object. ‘return’ statement stops the
execution of the function and sends the value back to the calling code. We can return more
than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from a
function.
Example:
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
Output:

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 41

Returned value from the function : 30

Variable Scope
The scope of a variable is defined as its range in the program under which it can be
accessed. In other words, "The scope of a variable is the portion of the program within
which it is defined and can be accessed."
PHP has three types of variable scopes:
a) Local variable
b) Global variable
c) Static variable
a) 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.
File: local_variable1.php
<?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
[A variable declaration outside the function with the same name is completely different
from the variable declared inside the function. Let's understand the local variables with the
help of an example:
File: local_variable2.php
<?php  
    function mytest()  
    {  
        $lang = "PHP";  
        echo "Web development language: " .$lang;  
    }  
    mytest();  
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 42

    //using $lang (local variable) outside the function will generate an error  
    echo $lang;  
?>  
Output:
Web development language: PHP
Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28]
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.
Example:
File: global_variable1.php
<?php  
    $name = "LuckyMilky";        //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: LuckyMilky
Variable outside the function: LuckyMilky
Note: Without using the global keyword, if you try to access a global variable inside the
function, it will generate an error that the variable is undefined.
Using $GLOBALS instead of global
Another way to use the global variable inside the function is predefined $GLOBALS array.
Example:
File: global_variable2.php
<?php  
    $num1 = 5;      //global variable  

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 43

    $num2 = 13;     //global variable  
    function global_var()  
    {  
            $sum = $GLOBALS['num1'] + $GLOBALS['num2'];  
            echo "Sum of global variables is: " .$sum;  
    }  
    global_var();  
?>  
Output:
Sum of global variables is: 18
Note: If two variables, local and global, have the same name, then the local variable has
higher priority than the global variable inside the function.
Example:
File: global_variable3.php
<?php  
$x = 5;  
function mytest()  
{  
$x = 7;  
echo "value of x: " .$x;  
}  
mytest();  
?>  
Output:
Value of x: 7
Static variable: It is a feature of PHP to delete the variable, once it completes its
execution and memory is freed. Sometimes we need to store a variable even after
completion of function execution. Therefore, another important feature of variable scoping
is static variable. We use the static keyword before the variable to define a variable, and
this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the
program execution leaves the scope.
Example:
File: static_variable.php
<?php  
    function static_var()  

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 44

    {  
        static $num1 = 3;       //static variable  
        $num2 = 6;          //Non-static variable  
        //increment in non-static variable  
        $num1++;  
        //increment in static variable  
        $num2++;  
        echo "Static: " .$num1 ."</br>";  
        echo "Non-static: " .$num2 ."</br>";  
    }  
      
//first function call  
    static_var();  
  
    //second function call  
    static_var();  
?>  
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
In the above example, $num1 regularly increments after each function call, whereas $num2
does not. This is why because $num1 is not a static variable, so it freed its memory after
the execution of each function call.

Saving state between Function calls with the static statement: Variables within
functions have a short but happy life on the whole. They come into being when the function
is called and die when execution is finished. But, if we want a function to keep track of the
number of times it has been called, it can be done in two ways as shown below.

 Using the global Statement to Remember the Value of a Variable Between Function Calls


 Using the static Statement to Remember the Value of a Variable Between Function Calls
Example: Using the global Statement to Remember the Value of a Variable Between
Function Calls
<html>
<head>
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 45

<title>Example</title>
</head>
<body>
<?php
$num_of_calls = 0;
function numberedHeading( $txt )
{
global $num_of_calls;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>";
}
numberedHeading("Widgets");
print("We build a fine range of widgets<p>");
numberedHeading("Doodads");
print("Finest in the world<p>");
?>
</body>
</html>
Put these lines into a text file called numberedheading.php, and place this file in Web
server document root. When we access this script through our Web browser, it should look
like:

This does the job. We declare a variable, $num_of_calls, in line 7, outside the


function numberedHeading(). We make this variable available to the function using
the global statement in line 9. Widget s doodads
Every time numberedHeading() is called, $num_of_calls is incremented (line 10). We can
then print out a heading complete with a heading number.
This is not the most elegant solution, however. Functions that use the global statement
cannot be read as standalone blocks of code. In reading or reusing them, we need to look
out for the global variables that they manipulate.
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 46

This is where the static statement can be useful. If we declare a variable within a function


in conjunction with the static statement, the variable remains local to the function, and the
function "remembers" the value of the variable from execution to execution. The following
example shows the use of static statement.
Example: Using the static Statement to Remember the Value of a Variable Between
Function Calls
<html>
<head>
<title>Listing 6.10</title>
</head>
<body>
<?php
function numberedHeading( $txt )
{
static $num_of_calls = 0;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>";
}
numberedHeading("Widgets");
print("We build a fine range of widgets<p>");
numberedHeading("Doodads");
print("Finest in the world<p>");
?>
</body>
</html>

numberedHeading() has become entirely self-contained. When we declare


the $num_of_calls variable on line 8, we assign an initial value to it. This assignment is made
when the function is first called on line 12. This initial assignment is ignored when the
function is called a second time on line 14. Instead, the code remembers the previous value
of $num_of_calls. We can now paste the numberedHeading() function into other scripts
without worrying about global variables. Although the output of above code is exactly the
same as that of previous code, we have made the code more elegant.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 47

More About Arguments


PHP Functions with Parameters

PHP gives us option to pass our parameters inside a function. We can pass as many as
parameters we like. These parameters work like variables inside our function. Following
example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Output:
Sum of the two numbers is : 30

Passing Arguments by Reference

PHP Functions with Parameters using Reference:

It is possible to pass arguments to functions by reference. This means that a reference to


the variable is manipulated by the function rather than a copy of the variable's value. Any
changes made to an argument in these cases will change the value of the original variable.
We can pass an argument by reference by adding an ampersand to the variable name in
either the function call or the function definition.
Example: Following example depicts both the cases.

<html>
<head>

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 48

<title>Passing Argument by Reference</title>


</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$original_num = 10;
addFive( $original_num );
echo "Original Value is $orignum<br />";
addSix( $original_num );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
Output:
Original Value is 10
Original Value is 16

Setting Default Values for Function Parameters

We can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 49

function printMe($param = NULL)


{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
Output:

This is test

Dynamic Function Calls: It is possible to assign function names as strings to variables and
then treat these variables exactly as the function name itself. Following example depicts
this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Output:

Hello

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 50

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 51

Testing for the Existence of a Function: The function_exists() is an inbuilt function


in PHP. The function_exists() function is useful in case if we want to check whether a
function() exists or not in the PHP script. It is used to check for both built-in functions as
well as user-defined functions.
Syntax:
boolean function_exists($function_name)

Parameter: This function accepts a single parameter $function_name. This is the name of


function that we want to search in the list of defined function. This is a string type
parameter.
Return Values: This function returns a Boolean value. In case a function with the name
$function_name exists it returns TRUE, otherwise it returns FALSE. This function will
also return FALSE for constructs like “include_once”, “echo” etc.
Example:
<?php
// checking if the in_array() built-in function
// exists or not
if (function_exists('in_array'))
{
echo "in_array() function is available.\n";
}
else
{
echo "in_array() function is not available.\n";
}
?>
Output:
in_array() function is available.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 52

Unit-II
Working with Arrays
What are Arrays? Types of Arrays?
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its
easy to define an array of 100 length.

Creating Arrays: We can create an array using either the array() function or the
array operator []. The array() function is usually used when we want to create a new
array and populate it with more than one element, all in one attempt. The array
operator is often used when you want to create a new array with just one element
at a time.

Types of Arrays: There are three different kinds of arrays and each array value is
accessed using an ID which is called array index or key.

a) Numeric array 
b) Associative array 
c) Multidimensional array 

a) Numeric Array: These arrays can store numbers, strings and any object but their index
will be represented by numbers. By default array index starts from zero. There are two
ways to create arryas. They are,

Method-1: Here we have used array() function to create array.

Method-2: By directly assigning values to an array.


Example: Following is the example showing how to create and access numeric arrays.

<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 53

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )


{
echo "Value is $value <br />";
}
?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
b) Associative Arrays: The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index. Associative array will have
their index as string so that we can establish a strong association between key and
values.

For example, to store the salaries of employees in an array, a numerically indexed array
would not be the best choice. Instead, we could use the employees names as the keys in
our associative array, and the value would be their respective salary.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 54

NOTE – We should not keep associative array inside double quotes while printing otherwise
it would not return any value.

Example:
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Lucky" => 40000, "Milky" => 50000, "Chinnu" => 60000);

echo "Salary of Lucky is ". $salaries['Lucky'] . "<br />";


echo "Salary of Milky is ". $salaries['Milky']. "<br />";
echo "Salary of zara is ". $salaries['Chinnu']. "<br />";
/* Second method to create array. */
$salaries['Lucky'] = "Low";
$salaries['Milky'] = "Medium";
$salaries['Chinnu'] = "High";
echo "Salary of Lucky is ". $salaries['Lucky'] . "<br />";
echo "Salary of Milky is ". $salaries['Milky']. "<br />";
echo "Salary of Chinnu is ". $salaries['Chinnu']. "<br />";
?>
</body>
</html>
Output:
Salary of Lucky is 40000
Salary of Milky is 50000
Salary of Chinnu is 60000
Salary of Lucky is Low
Salary of Milky is Medium
Salary of Chinnu is High

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 55

c) Multidimensional Arrays: A multi-dimensional array each element in the main array can
also be an array. And each element in the sub-array can be an array, and so on. Values in
the multi-dimensional array are accessed using multiple indexes.

Example: In this example we create a two dimensional array to store marks of three
students in three subjects −
<html>
<body>
<?php
$marks = array(
"Lucky" => array ("C_Lang" => 74,"Java" => 73, "PHP" => 73),
"Milky" => array ("C_Lang" => 73, "Java" => 73,"PHP" => 71),
"Chinnu" => array ("C_Lang" => 31,"Java" => 22,"PHP" => 72)
);
/* Accessing multi-dimensional array values */
echo "Marks for Lucky in C_Lang : " ;
echo $marks['Lucky']['C_Lang'] . "<br />";
echo "Marks for Milky in Java : ";
echo $marks['Milky']['Java'] . "<br />";
echo "Marks for Chinnu in PHP : " ;
echo $marks['Chinnu']['PHP'] . "<br />";
?>
</body>
</html>
Output:

Marks for Lucky in C_Lang : 74


Marks for Milky in Java : 73
Marks for Chinnu in PHP : 72

Some Array-Related Functions

More than 70 array-related functions are built in to PHP, which we can read about
in detail at http://www.php.net/array. Some of the more common (and useful)
func- tions are given below.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 56

a) count() and sizeof(): Each of these functions counts the number of elements in an
array. They are aliases of each other. Consider the following array.

Example: $colors = array(“blue”, “black”, “red”, “green”);


Both count($colors); and sizeof($colors); return a value of 4.
b) array_push(): This function adds one or more elements to the end of an
existing array, as in this example:

Example: array_push($existingArray, “element 1”, “element 2”, “element 3”);


c) array_pop(): This function removes (and returns) the last element of an
existing array, as in this example:

Example: $last_element = array_pop($existingArray);


d) array_unshift(): This function adds one or more elements to the beginning of
an existing array, as in this example:

Example: array_unshift($existingArray, “element 1”, “element 2”, “element 3”);


e) array_shift(): This function removes (and returns) the first element of an
existing array, as in this example, where the value of the element in the first
position of $existingArray is assigned to the variable $first_element:

Example: $first_element = array_shift($existingArray);


f) array_merge(): This function combines two or more existing arrays, as in this
example:

Example: $newArray = array_merge($array1, $array2);


g) array_keys(): This function returns an array containing all the key names within
a given array, as in this example:

Example: $keysArray = array_keys($existingArray);


h) array_values(): This function returns an array containing all the values within a
given array, as in this example:

Example: $valuesArray = array_values($existingArray);


i) shuffle():This function randomizes the elements of a given array. The syn- tax
of this function is simply as follows:

Example: shuffle($existingArray);

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 57

j) reset(): This function rewinds the pointer to the beginning of an array, as in


this example:

Example: reset($character);
This function proves useful when you are performing multiple manipulations on
an array, such as sorting, extracting values, and so forth.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 58

Working with Objects

Object Oriented Concepts: Important terms related to Object Oriented Programming are
defined below.
a) Class: This is a programmer-defined data type, which includes local functions as well as
local data. We can think of a class as a template for making many instances of the same
kind (or class) of object.

b) Object: An individual instance of the data structure defined by a class. We define a


class once and then make many objects that belong to it. Objects are also known as
instance.

c) Member Variable: These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.

d) Member function: These are the function defined inside a class and are used to access
object data.

e) Inheritance: Deriving a new class from an existing class is called as inheritance. Here
child class will inherit all or few member functions and variables of a parent class.

f) Parent class: A class that is inherited by another class. This is also called a base class or
super class.

g) Child Class: A class that inherited from another class. This is also called a subclass or
derived class.

h) Polymorphism: This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it take different
number of arguments and can do different task.

i) Overloading: A type of polymorphism in which some or all of methods have different


implementations depending on the types of their arguments. Similarly operators can also
be overloaded with different operations.

j) Data Abstraction: Any representation of data in which the implementation details are
hidden (abstracted).

k) Encapsulation: Refers to a concept where we encapsulate(bind) all the data and member
functions together to form an object.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 59

l) Constructor: Refers to a special type of function which will be called automatically


whenever there is an object formation from a class.

m) Destructor: Refers to a special type of function which will be called automatically


whenever an object is deleted or goes out of scope.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 60

Defining PHP Classes: The general form for defining a new class in PHP is as follows.
Syntax:
<?php
class ClassName
{
DataMembers/Field declarations;
MemberFunctions/methods;
}
?>
In the above syntax,

 ‘class’ is a keyword, followed by the name of the class that you want to define.
 The curly braces indicate beginning and ending of class definition. And class
definition includes variable declarations and function definitions.
 Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a constant
value.
 Function definitions look much like standalone PHP functions but are local to the class
and will be used to set and access object data.
Example: Here is an example which defines a class of Books type.
<?php
class Books
{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 61

function setTitle($par)
{
$this->title = $par;
}
function getTitle()
{
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP Once we defined our class, then we can create as many objects as
we like of that class type. Following is an example of how to create object
using new operator.
$C_Programming = new Books;
$OOP_Through_Java = new Books;
$DataStructures = new Books;
Here we have created three objects and these objects are independent of each other and
they will have their existence separately.

Calling Member Functions: After creating objects, we can call member functions related to
that object. One member function will be able to process member variable of related object
only. Following example shows how to set title and prices for the three books by calling
member functions.
$C_Programming->setTitle( "C_Programming for Data Science" );
$DataStructures->setTitle( " DataStructures" );
$OOP_Through_Java->setTitle( "Java for Data Science" );

$C_Programming->setPrice( 1000 );
$DataStructures->setPrice( 1500 );
$OOP_Through_Java->setPrice( 1300 );
Now we can call another member functions to get the values set by in above example as
follows.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 62

$C_Programming->getTitle();
$DataStructures->getTitle();
$OOP_Through_Java->getTitle();
$C_Programming->getPrice();
$DataStructures->getPrice();
$OOP_Through_Java->getPrice();
This will produce the following output:
C_Programming for Data Science
DataStructures
Java for Data Science
1000
1500
1300

Constructor Functions: Constructor Functions are special type of functions which are
called automatically whenever an object is created. So we take full advantage of this
behaviour, by initializing many things through constructor functions.

PHP provides a special function called __construct() to define a constructor. We can pass as


many as arguments we like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and
title for the book at the time of object creation.

function __construct( $par1, $par2 )


{
$this->title = $par1;
$this->price = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize
these two member variables at the time of object creation only. Consider the example
below.

$C_Programming = new Books( "C_Programming for Data Science", 1000 );


$OOP_Through_Java = new Books ( "DataStructures", 15000);
$DataStructures = new Books ("Java for Data Science", 1300 );

/* Get those set values */


$C_Programming->getTitle();

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 63

$DataStructures->getTitle();
$OOP_Through_Java->getTitle();
$C_Programming->getPrice();
$DataStructures->getPrice();
$OOP_Through_Java->getPrice();
This will produce the following output:

C_Programming for Data Science


DataStructures
Java for Data Science
1000
1500
1300
Destructor: Like a constructor function we can define a destructor function using
function __destruct(). We can release all the resources with-in a destructor.
Inheritance: PHP class definitions can optionally inherit from a parent class definition by
using the extends clause. The syntax is as follows −
Syntax:
class Child extends Parent
{
<definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the
following characteristics −
 Automatically has all or some of the member variable declarations of the parent
class.
 Automatically has all or some of the same member functions as the parent, which
(by default) will work the same way as those functions do in the parent.
Following example inherits Books class and adds more functionality based on the
requirement.
class Course extends Books
{
var $publisher;
function setPublisher($par)
{
$this->publisher = $par;
}
function getPublisher()

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 64

{
echo $this->publisher. "<br />";
}
}
Now apart from inherited functions, class Course keeps two additional member functions.

Function Overriding: Function definitions in child classes override definitions with the
same name in parent classes. In a child class, we can modify the definition of a function
inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return some
values.

function getPrice()
{
echo $this->price . "<br/>";
return $this->price;
}
function getTitle()
{
echo $this->title . "<br/>";
return $this->title;
}

Public Members: Unless we specify otherwise, properties and methods of a class are public.
That is to say, they may be accessed in three possible situations −
 From outside the class in which it is declared
 From within the class in which it is declared
 From within another class that implements the class in which it is declared
We need not to declare all the members as public, if we need to limit the accessibility of
the members of a class then we define class members as private or protected.

Private members: By designating a member private, we limit its accessibility to the class in
which it is declared. The private member cannot be referred to from classes that inherit
the class in which it is declared and cannot be accessed from outside the class.

A class member can be made private by using private keyword infront of the member.


Example:

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 65

class MyClass
{
private $safe = "secured"; // available only with in the class.
$common = "unsecured"; // can be used even outside the classs

function __construct($par)
{
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() // public method can be used every where
{
return("I'm visible!");
}
private function myPrivateFunction()// private, can be used within the class
{
return("I'm not visible outside!");
}
}

Protected members: A protected property or method is accessible in the class in which it


is declared, as well as in classes that extended that class. Protected members are not
available outside of those two kinds of classes. A class member can be made protected by
using protected keyword in front of the member.

Example:
class MyClass
{
protected $p = "safe";
$q = "unsafe";

function __construct($par) {
// Statements here run every time
// an instance of the class

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 66

// is created.
}

function myPublicFunction() {
return("I'm visible!");
}

protected function myPrivateFunction() {


return("I'm visible here and in child class only!");
}
}

Interfaces: Interfaces are defined to provide a common function names to the


implementers. Different implementors can implement those interfaces according to their
requirements. We can say, interfaces are skeletons which are implemented by developers.

As of PHP5, it is possible to define an interface as follows.


interface Mail
{
public function sendMail();
}
Then, if another class implemented that interface, like this −

class Report implements Mail


{
// sendMail() Definition goes here
}

Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a
function because a constant is immutable. Once we declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of MyClass −

class MyClass
{
const PIE = 3.14;

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 67

function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}
In this class, PIE is a constant. It is declared with the keyword const, and under no
circumstances can it be changed to anything other than 3.14. Note that the constant's name
does not have a leading $, as variable names do.

Abstract Classes: An abstract class is one that cannot be instantiated, only inherited. We
can declare an abstract class with the keyword abstract.

When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child; additionally, these methods must be defined with
the same visibility.

abstract class MyAbstractClass


{
abstract function myAbstractFunction()
{
}
}
Note: Function definitions inside an abstract class must also be preceded by the keyword
abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword: Declaring class members or methods as static makes them accessible
without needing an instantiation of the class. A member declared as static can not be
accessed with an instantiated class object (though a static method can).

Example:

<?php
class Test
{
public static $my_static = 'fun';
public function staticValue()
{
return self::$my_static;
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 68

}
}
print Test::$my_static . "\n";
$t = new Test();
print $t->staticValue() . "\n";
?>

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method
by prefixing the definition with final. If the class itself is being defined final then it cannot
be extended.

Following example results in Fatal error: Cannot override final method


BaseClass::moreTesting()

<?php
class BaseClass
{
public function test()
{
echo "BaseClass::test() called<br>";
}
final public function moreTesting()
{
echo "BaseClass::moreTesting() called<br>";
}
}
class ChildClass extends BaseClass
{
public function moreTesting()
{
echo "ChildClass::moreTesting() called<br>";
}
}
?>

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 69

Calling parent constructors: Instead of writing an entirely new constructor for the
subclass, we can write it by calling the parent's constructor explicitly and then doing
whatever is necessary in addition for instantiation of the subclass.
Example:
class Name
{
var $_firstName;
var $_lastName;

function Name($first_name, $last_name)


{
$this->_firstName = $first_name;
$this->_lastName = $last_name;
}
function toString()
{
return($this->_lastName .", " .$this->_firstName);
}
}

class NameSub1 extends Name


{
var $_middleInitial;
function NameSub1($first_name, $middle_initial, $last_name)
{
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
function toString()
{
return(Name::toString() . " " . $this->_middleInitial);
}
}

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430
OM SAIRAM 70

In this example, we have a parent class (Name), which has a two-argument constructor, and
a subclass (NameSub1), which has a three-argument constructor. The constructor of
NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing
two of its arguments along) and then setting an additional field. Similarly, NameSub1
defines its non constructor toString() function in terms of the parent function that it
overrides.

Working with Strings, Dates and Time

Unit-2: (10 hours)


Working with Arrays: What are Arrays? Creating Arrays, Some Array-Related
Functions. Working with Objects: Creating Objects, Object Instance Working with
Strings, Dates and Time: Formatting strings with PHP, Investigating Strings with PHP,
Manipulating Strings with PHP, Using Date and Time Functions in PHP.

V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]


Mobile:9966074430

You might also like