0% found this document useful (0 votes)
35 views22 pages

PHP Unit 2 Econtent

UNIT-II Working with Arrays: Creating Arrays, Some Array-Related Functions. Working with Objects: Creating Objects, Accessing Object Instances, Working with Strings, Dates and Time: Formatting strings with PHP, Manipulating Strings with PHP, Using Date and Time Functions in 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)
35 views22 pages

PHP Unit 2 Econtent

UNIT-II Working with Arrays: Creating Arrays, Some Array-Related Functions. Working with Objects: Creating Objects, Accessing Object Instances, Working with Strings, Dates and Time: Formatting strings with PHP, Manipulating Strings with PHP, Using Date and Time Functions in 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/ 22

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 II
ARRAYS
Arrays: An array is a collection of similar types of data. It is used to hold multiple values of similar type in a
single variable.
Advantage of PHP Array:
1. Less Code: We don't need to define multiple variables.
2. Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
3. Sorting: We can sort the elements of array.
TYPES OF ARRAYS IN PHP: There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1. Indexed Array: PHP indexed array is an array which is represented by an index number by default. All
elements of array are represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric
array. There are two ways to define indexed array:
1st way:
Example:
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
2nd way:
Example:
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Department of Computer Science Web Applications Development using PHP& MYSQL Page 1
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
2. Associative Array: PHP allows you to associate name/label with each array elements in PHP using =>
symbol. Such way, you can easily remember the element because each element is represented by label than
an incremented number. There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
Example:
<?php
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 2
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
3. Multidimensional Array: PHP multidimensional array is also known as array of arrays. It allows you to
store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
Example:
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP ARRAY FUNCTIONS: PHP provides various array functions to access and manipulate the elements
of array. The important PHP array functions are given below.
1) PHP array() function: PHP array() function creates and returns an array. It allows you to create indexed,
associative and multidimensional arrays.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 3
Syntax:
array array ([ mixed $... ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
OUTPUT:
Season are: summer, winter, spring and autumn
2) PHP count() function: PHP count() function counts all elements in an array.
Syntax:
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
OUTPUT:
4
3) PHP sort() function: PHP sort() function sorts all the elements in an array.
Syntax:
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>
OUTPUT:
autumn

Department of Computer Science Web Applications Development using PHP& MYSQL Page 4
spring
summer
winter
4) PHP array_reverse() function:PHP array_reverse() function returns an array containing elements in
reversed order.
Syntax
array array_reverse ( array $array [, bool $preserve_keys = false ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
OUTPUT:
autumn
spring
winter
summer
5) PHP array_search() function: PHP array_search() function searches the specified value in an array. It
returns key if search is successful.
Syntax
mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
OUTPUT:
2

Department of Computer Science Web Applications Development using PHP& MYSQL Page 5
ADVANTAGES AND DISADVANTAGES OF ARRAYS
Advantages of Array
 Arrays help in code optimization. We can store a large number of values in a single array by writing a
small piece of code rather than declaring each variable separately.
 Arrays store elements in a sequential manner in memory locations, so no extra memory is allocated
thus preventing the wastage of memory.
 Using arrays, other data structures like linked lists, stacks, queues, trees, graphs etc can be
implemented.
Disadvantages of Array
 The size of an array is fixed. Once the memory is allocated to an array, it cannot be increased or
decreased. This prevents us from storing extra data in case we want to. These arrays of fixed size are
called static arrays.
 A single array cannot store values of different data types, i.e, an array is homogenous in nature.
 Allocating less memory than the required to an array leads to loss of data.
 Allocating more memory than the requirement leads to wastage of memory space and less allocation
of memory also leads to a problem.
WORKING WITH OBJECTS
PHP WITH OOPS CONCEPT
Object-oriented programming is a programming model organized around Object rather than the
actions and data rather than logic.
Class: A class is an entity that determines how an object will behave and what the object will contain. In
other words, it is a blueprint or a set of instruction to build a specific type of object.

This is the blueprint of the Vehicle that is class, and the Box truck,Sports cae, Sedan car and Pickup truck
are the objects of Vehicle.
In PHP, declare a class using the class keyword, followed by the name of the class and a set of curly braces
({}).

Department of Computer Science Web Applications Development using PHP& MYSQL Page 6
Syntax to Create Class in PHP
<?php
class MyClass
{
// Class properties and methods go here
}
?>
Object: Objects are real time entities. Objects are determined from classes in Object-Oriented Programming
like PHP. When a class is specified, we can create any number of objects out of the class.
Example: If Vehicle is the class, then Box truck, Sports car, Sedan car and Pickup truck are the objects of
the Class Vehicle.

Creating an object: Following is an example of how to create object using new operator.
Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
?>
Example of class and object:
<?php
class SayHello
{
function hello()
{
echo "Hello World";

Department of Computer Science Web Applications Development using PHP& MYSQL Page 7
}
}
$obj=new SayHello;
$obj->hello();
?>
Output:
Hello World
Output:
INHERITANCE: It is a concept of accessing the features from one class to another class. If we inherit the
class features into another class, we can access both class properties. We can extends the features of a class
by using 'extends' keyword.
 It supports the concept of hierarchical classification.
 Inheritance has three types, single, multiple and multilevel Inheritance.
 PHP supports only single inheritance, where only one class can be derived from single parent
class.
 We can simulate multiple inheritance by using interfaces.
TYPES OF INHERITANCES: PHP offers mainly three types of inheritance based on their functionality.
These three types are as follows:
1. Single Inheritance: Deriving a class from only one base class(super class) is known as Single inheritance. In below
image, the class A serves as a base class for the derived class B.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 8
Example:
<?php
class demo
{
public function display()
{
echo "Example of inheritance ";
}
}
class demo1 extends demo
{
public function view()
{
echo "in php";
}
}
$obj= new demo1();
$obj->display();
$obj->view();
?>
Output:
Example of inheritance in php
2. Multilevel Inheritance: Deriving a class from another derived class is known as Multi level inheritance. In below
image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived
class C.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 9
Example:
<?php
class A
{
function showA()
{
echo "I am show method in A Class<br>";
}
}

class B extends A
{
function showB()
{
echo "I am show method in B Class<br>";
}
}
class C extends B
{
function showC()
{
echo "I am show method in C Class<br>";
}
}
$obj=new C;
$obj->showA();
$obj->showB();
$obj->showC();
?>
Output:
I am show method in A Class
I am show method in B Class
I am show method in C Class

Department of Computer Science Web Applications Development using PHP& MYSQL Page 10
3. Hierarchical Inheritance: Deriving several classes from one base class is known as Hierarchical
inheritance. In below image, the class A serves as a base class for the derived class B,C and D.

Example:
<?php
// base class named "Jewellery"
class Jewellery
{
public function show()
{
echo 'This class is Jewellery ';
}
}
// Derived class named "Necklace"
class Necklace extends Jewellery
{
public function show()
{
echo 'This class is Necklace ';
echo"<br>";
}
}
// Derived class named "Necklace"

Department of Computer Science Web Applications Development using PHP& MYSQL Page 11
class Bracelet extends Jewellery
{
public function show()
{
echo 'This class is Bracelet ';
}
}
// creating objects of derived classes "Necklace" and "Bracelet"
$n = new Necklace();
$n->show();
$b = new Bracelet();
$b->show();
?>
Output:
This class is Necklace
This class is Bracelet
ADVANTAGES AND DISADVANTAGES OF INHERITANCE
Advantages
1. The main advantage of the inheritance is that it helps in reusability of the code. The codes are defined
only once and can be used multiple times.
2. Through inheritance a lot of time and efforts are being saved.
3. The program structure is short and concise which is more reliable.
4. Inheritance makes the application code more flexible to change.
Disadvantages
1. The main disadvantage of the inheritance is that the two classes (base class and super class) are
tightly coupled that is the classes are dependent on each other.
2. If the functionality of the base class is changed then the changes have to be done on the child classes
also.
3. If the methods in the super class are deleted then it is very difficult to maintain the functionality of the
child class which has implemented the super class’s method.
4. It increases the time and efforts take to jump through different levels of the inheritance.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 12
FUNCTION OVERLOADING AND OVERRIDING:
Function Overloading: “If a class contains multiple methods with same name but different parameters is
kown as Method overloading.”

Function Overriding: Function overriding is same as other OOPs programming languages. In function
overriding, both parent and child classes should have same function name with and number of arguments.
It is used to replace parent method in child class. The purpose of overriding is to change the behavior of
parent class method. The two methods with the same name and same parameter is called overriding.
Example:
<?php
class Vehicle
{
function run()
{
echo "Vehicle is running<br>";
}
}
class Bike extends Vehicle
{
function run()
{
echo "Bike is running";
}
}
$v = new Vehicle;
$b= new Bike;
$v->run();
$b->run();
?>
Output:
Vehicle is running
Bike is running

Department of Computer Science Web Applications Development using PHP& MYSQL Page 13
INTERFACE
o An interface is similar to a class except that it cannot contain code.
o An interface can define method names and arguments, but not the contents of the methods.
o Any classes implementing an interface must implement all methods defined by the interface.
o A class can implement multiple interfaces.
o An interface is declared using the "interface" keyword.
o Interfaces can't maintain Non-abstract methods.
Example
<?php
interface circle
{
public function draw1();
}
interface rectangle
{
public function draw2();
}
class demo implements circle,rectangle
{
public function draw1()
{
echo "Drawing Circle";
echo "</br>";
}
public function draw2()
{
echo "Drawing Rectangle";
}
}
$obj= new demo();
$obj->draw1();
$obj->draw2();
?>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 14
Output:
Drawing Circle
Drawing Rectangle
PHP STRING: String is a sequence of characters i.e., used to store and manipulate text. There are four ways
of creating strings in PHP
Example 1
<?php
$str='Hello text within single quote';
echo $str;
?>
Output:
Hello text within single quote
Example 2
<?php
$str="Hello text within double quote";
echo $str;
?>
Output:
Hello text within double quote
FORMATTING STRINGS IN PHP:
printf() Function: If you are familiar with the C programming language, then you are probably familiar with
the printf() function. The printf() function requires a string argument, known as a format control string and it
also accepts additional arguments of various types.
Syntax:
printf(format,arg1,arg2,arg++);
Example:
<?php
$no=60;
printf("The integer is:%d",$no);
?>
Output: The integer is: 60

Department of Computer Science Web Applications Development using PHP& MYSQL Page 15
sprintf() Function: The sprintf() function is similar to the printf() function, but the only difference between
both of them is that sprint() saves the output into a string instead of displaying the formatted message on
browser like printf() function.
Syntax:
sprintf (format, agr1, agr2, arg3...) : string
Example:
<?php
$val = 299;
$txt = sprintf("%f",$val);
echo $txt;
?>
Output:
299.000000
STRING FUNCTIONS OR MANIPULATING STRINGS WITH PHP: PHP provides various string
functions to access and manipulate strings. A list of PHP string functions are given below.
1. strlen() Function: It returns the length of the string i.e. the count of all the characters in the string
including whitespaces characters.
Syntax:
strlen(string or variable name)
Example:
<?php
$str = "Hello World!";
// Prints 12 as output
echo strlen($str);
// Prints 13 in a new line
echo "<br>" . strlen("GeeksForGeeks");
?>
Output:
12
13
2. strrev() Function: It returns the reversed string of the given string.
Syntax:
strrev(string or variable name)

Department of Computer Science Web Applications Development using PHP& MYSQL Page 16
Example:

<?php
$str = "Hello World!";
echo strrev($str);
?>

Output:
!dlroW olleH
3. trim(), ltrim(), rtrim(), and chop() Functions: It remove white spaces or other characters from the
string. They have two parameters: one string and another charList, which is a list of characters that need to
be omitted.
 trim() – Removes characters or whitespaces from both sides.
 rtrim() & chop() – Removes characters or whitespaces from right side.
 ltrim() – Removes characters or whitespaces from the left side.
Syntax:
rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)
Example:
<?php
$str = "\nThis is an example for string functions.\n";
// Prints original string
echo $str. "<br>";
// Removes whitespaces from right end
echo chop($str) . "<br>";
// Removes whitespaces from both ends
echo trim($str) . "<br>";
// Removes whitespaces from right end
echo rtrim($str) . "<br>";
// Removes whitespaces from left end
echo ltrim($str);
?>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 17
Output:
This is an example for string functions.
This is an example for string functions.
This is an example for string functions.
This is an example for string functions.
This is an example for string functions.
4. strtoupper() Function: The strtoupper() function returns string in uppercase letter.
Syntax:
strtoupper (string)
Example:
<?php
$str="Dnr College";
$str=strtoupper($str);
echo $str;
?>
Output:
DNR COLLEGE
5. strtolower() function: The strtolower() function returns string in lowercase letter
Syntax:
strtolower(string)
Example:
<?php
$str="Dnr College";
$str=strtolower($str);
echo $str;
?>
Output:
dnr college
6. ucfirst() function: The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.
Syntax
ucfirst(strin )
Example

Department of Computer Science Web Applications Development using PHP& MYSQL Page 18
<?php
$str="dNR College";
$str=ucfirst($str);
echo $str;
?>
Output:
DNR College
7. lcfirst() function: The lcfirst() function returns string converting first character into lowercase. It doesn't
change the case of other characters.
Syntax
string lcfirst ( string $str )
Example
<?php
$str="Dnr College";
$str=lcfirst($str);
echo $str;
?>
Output:
dnr College
8. ucwords() function: The ucwords() function returns string converting first character of each word into
uppercase.
Syntax
string ucwords ( string $str )
Example
<?php
$str="dnr college bhimavaram";
$str=ucwords($str);
echo $str;
?>
Output:
Dnr College Bhimavaram
9. strcmp() Function: The strcmp() function is used to compare two strings. It returns true if two strings are
equal otherwise returns false.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 19
Syntax:
strcmp(string1,string2)
Example:
<html>
<body>
<?php
echo strcmp("Hello world!","Hello world!");
?>
<p>If this function returns 0, the two strings are equal.</p>
</body>
</html>
Output:
0
If this function returns 0, the two strings are equal.
DATE AND TIME FUNCTIONS IN PHP: The date/time functions allow you to get the date and time from the
server where your PHP script runs. You can then use the date/time functions to format the date and time in
several ways. Some of the predefined functions in PHP for date and time are discussed below.
PHP date() Function: The PHP date() function converts timestamp to a more readable date and time
format.
Syntax:
date(format, timestamp)
Explanation:
The format parameter in the date() function specifies the format of returned date and time.
The timestamp is an optional parameter, if it is not included then the current date and time will be used.
Example:

<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>

Output:
Today's date is :05/12/2017

Department of Computer Science Web Applications Development using PHP& MYSQL Page 20
Example 2:
<?php
echo "Today's date in various formats:" . "\n";
echo date("d/m/Y") . "\n";
echo date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>
Output:
Today's date in various formats:
05/12/2017
05-12-2017
05.12.2017
05.Dec.2017/Tue
PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the number
of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
Example: The below example explains the usage of the time() function in PHP.

<?php
$timestamp = time();
echo($timestamp);
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
Output:
1512486297
December 05, 2017 03:04:57 PM

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

You might also like