Unit-II
Syllabus
Working with Arrays: 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.
………………………………………………………………………………………………………………………………………………………………………………………….
1. What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
2. Create an Array in PHP
In PHP, the array() function is used to create an array:
Ex: $cars = array("Volvo", "BMW", "Toyota");
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
1. The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
2. The index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example Program:- The following example creates an indexed array named $cars, assigns three elements to it, and then
prints a text containing the array values
1 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
1. $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
2. $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays. PHP understands multidimensional arrays that are
two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most
people.
A multidimensional array holds more than one series of these key/value pairs.
Example.
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
2 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
3. Some Array-Related Functions
More than 70 array-related functions are built in to PHP. Some of the more common (and useful) functions
are described briefly below.
1. count() and sizeof()—Each of these functions counts the number of elements in an array; they are aliases of each
Other. Given the following array.
Example:
$colors = array(“blue”, “black”, “red”, “green”);
both count($colors); and sizeof($colors); return a value of 4.
2. each() and list()—These functions usually appear together, in the context of stepping through an array and returning
its keys and values.
Example:
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
3. foreach()—This control structure (that looks like a function) is used to step through an array.
Example:
foreach ($characters as $c) {
while (list($k, $v) = each ($c)) {
echo “$k ... $v <br/>”;
}
echo “<hr/>”;
}
4. reset()—This function rewinds the pointer to the beginning of an array.
example: reset($character);
This function proves useful when you are performing multiple manipulations on an array, such as sorting, extracting
values, and so forth.
5. array_push()—This function adds one or more elements to the end of an existing array.
example: array_push($existingArray, “element 1”, “element 2”, “element 3”);
6. array_pop()—This function removes (and returns) the last element of an existing array.
Example: $last_element = array_pop($existingArray);
7. array_unshift()—This function adds one or more elements to the beginning of an existing array.
Example: array_unshift($existingArray, “element 1”, “element 2”, “element 3”);
8. array_shift()—This function removes (and returns) the first element of an existing array.
Example: $first_element = array_shift($existingArray);
3 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
8. array_merge()—This function combines two or more existing arrays.
Example: $newArray = array_merge($array1, $array2);
9. array_keys()—This function returns an array containing all the key names within a given array.
Example: $keysArray = array_keys($existingArray);
10. array_values()—This function returns an array containing all the values within a given array.
Example: $valuesArray = array_values($existingArray);
11. shuffle()—This function randomizes the elements of a given array. The syntax of this function is simply as follows:
shuffle($existingArray)
------------------ ###---------------------------------
Questions:
What is an Array? How to create different types of arrays in PHP? Explain.
Define Array? Write about some array related functions with examples.
4 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
Chapter-II (Working with Objects)
Syllabus: Creating Objects, Object Instance.
--------------------------------------------------------------------------------------------
Introduction:
Programmers use objects to store and organize data. Object-oriented programming is a type of programming in which
the structure of the program (or application) is designed around these objects and their relationships and interactions.
Object-oriented programming structures are found in many programming languages, and are also evident in PHP. In
fact, many PHP programmers—especially those coming from a highly object-oriented programming background—
choose to develop PHP applications in an object-oriented way.
1. Creating Objects in PHP.
PHP is a server-side scripting language, mainly used for web development but also used as a general-purpose
programming language. Object-Oriented Programming (PHP OOP), is a type of programming language principle added
to php5 that helps in building complex, reusable web applications.
Class & Object:
• Class is a programmer-defined data type, which includes local methods and local variables.
• Class is a collection of objects. Object has properties and behavior.
• First we have to define a php class, where classname should be same as filename.
Example for simple class:
<?php
class Books{
public function name()
{
echo “Drupal book”;
}
public function price()
{
echo “900 Rs/-”;
}
}
// To create php object we have to use a new operator. Here php object is the object of the Books Class.
$obj = new Books();
$obj->name();
$obj->price();
?>
When class is created, we can create any number of objects to that class. The object is created with the help of new
keyword.
5 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
Calling Member Function.
When the object is created we can access the variables and method function of the class with the help of operator ‘->,
accessing the method is done to get the information of that method.
<?php
class Mobile {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setName($par){
$this->title = $par;
}
function getName(){
echo $this->title ." <br/>";
}
}
$Samsung = new Mobile();
$Xiaomi = new Mobile();
$Iphone = new Mobile();
$Samsung->setName( "SamsungS8 );
$Iphone->setName( "Iphone7s" );
$Xiaomi->setName( "MI4" );
$Samsung->setPrice( 90000 );
$Iphone->setPrice( 65000 );
$Xiaomi->setPrice( 15000 );
Now you call another member functions to get the values set by in above example
$Samsung->getName();
$Iphone->getName();
$Xiaomi->getName();
$Samsung->getPrice();
$Iphone->getPrice();
$Xiaomi->getPrice();
?>
6 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
2. Object Instance
When the properties and the methods of the parent class are accessed by the child class, we call the concept has
inheritance. The child class can inherit the parent method and give own method implementation, this property is called
overridden method. When the same method of the parent class is inherited we call as inherited method. Now let us see
types of inheritance supported in Object Oriented Programming and corresponding Php inheritance examples.
Types Of Inheritance
1. Single Level Inheritance
2. Multilevel Inheritance
Single Level Inheritance: In Single Level Inheritance the Parent class methods will be extended by the child class. All
the methods can be inherited.
<?php
class A {
public function printItem($string)
{
echo ' Hi : ' . $string;
}
public function printPHP()
{
echo 'I am from valuebound' . PHP_EOL;
}
}
class B extends A {
public function printItem($string) {
echo 'Hi: ' . $string . PHP_EOL;
}
public function printPHP() {
echo "I am from ABC";
}
}
$a = new A();
$b = new B();
$a->printItem('Raju');
$a->printPHP();
$b->printItem('savan');
$b->printPHP();
?>
7 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
MultiLevel Inheritance: In MultiLevel Inheritance, the parent class method will be inherited by child class and again
subclass will inherit the child class method.
<?php
class A {
public function myage() {
return ' age is 80';
}
}
class B extends A {
public function mysonage() {
return ' age is 50';
}
}
class C extends B {
public function mygrandsonage() {
return 'age is 20';
}
public function myHistory() {
echo "Class A " .$this->myage();
echo "Class B ".$this-> mysonage();
echo "Class C " . $this->mygrandsonage();
}
}
$obj = new C();
$obj->myHistory();
?>
…………………######################.....................
Questions:
1. Discuss about working with objects in PHP
2. Discuss about object Inheritance.
8 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
Chapter-III (Working with Strings, Dates and Time)
Syllabus: Formatting Strings with PHP, Investigating Strings with PHP, Manipulating Strings with PHP, Using Date and
Time Functions in PHP.
………………………………………………………………………………………………………………………………………………………………………………………….
1. Formatting Strings with PHP
The printf() and sprintf() functions that you can use to format strings in many different ways. These functions are handy
when you need convert data between different formats — either to make it easy for people to read, or for passing to
another program.
PHP features many other functions to format strings in specific ways — for example, the date() function is ideal for
formatting date strings. However, printf() and sprintf() are great for general-purpose formatting.
Working with printf()
printf() requires a string argument, known as a format control string. It also accepts additional arguments of different
types. The format control string contains instructions indicating how to display these additional arguments.
The following snippet, for example, uses printf() to output an integer as a decimal:
printf("This is my number: %d", 55);
// prints "This is my number: 55"
A conversion specification begins with a percent (%) symbol and defines how to treat the corresponding argument to
printf(). You can include as many conversion specifications as you want within the format control string, as long as you
send an equivalent number of arguments to printf().
Table 13.1 lists the other available type Specifier.
Specifier Description
d Display argument as a decimal number
b Display an integer as a binary number
c Display an integer as ASCII equivalent
f Display an integer as a floating-point number (double)
o Display an integer as an octal number (base 8)
s Display argument as a string
x Display an integer as a lowercase hexadecimal number (base 16)
X Display an integer as an uppercase hexadecimal number (base 16)
9 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
Examples: Demonstrating Some Type Specifier
<html>
<head>
<title>Listing 13.1 Demonstrating some type Specifier</title>
</head>
<body>
<?php
$number = 543;
printf( "Decimal: %d<br>", $number );
printf( "Binary: %b<br>", $number );
printf( "Double: %f<br>", $number );
printf( "Octal: %o<br>", $number );
printf( "String: %s<br>", $number );
printf( "Hex (lower): %x<br>", $number );
printf( "Hex (upper): %X<br>", $number );
?>
</body>
</html>
Out Put:
10 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
Padding Output with the Padding Specifier
You can require that output be padded by leading characters. The padding specifier should directly follow the percent
sign that begins a conversion specification. To pad output with leading zeros, the padding specifier should consist of a
zero followed by the number of characters you want the output to take up. If the output occupies fewer characters
than this total, the difference will be filled with zeros:
Example-1:
printf( "%04d", 36 );
// prints "0036"
To pad output with leading spaces, the padding specifier should consist of a space character followed by the number of
characters that the output should occupy:
Example-2:
printf( "% 4d", 36 )
// prints " 36"
Specifying a Field Width
You can specify the number of spaces within which your output should sit. The field width specifier is an integer that
should be placed after the percent sign that begins a conversion specification (assuming that no padding specifier is
defined). The following snippet outputs a list of four items, all of which sit within a field of 20 spaces. To make the
spaces visible on the browser, we place all our output within a PRE element:
Example:
print "<pre>";
printf("%20s\n", "Books");
printf("%20s\n", "CDs");
printf("%20s\n", "Games");
printf("%20s\n", "Magazines");
print "</pre>";
11 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
Storing a Formatted String
The printf() function outputs data to the browser, which means that the results are not available to your scripts. You
can, however, use the function sprintf(), which works in exactly the same way as printf() except that it returns a string
that you can then store in a variable for later use. The following snippet uses sprintf() to round a double to two decimal
places, storing the result in $dosh:
Example:
$dosh = sprintf("%.2f", 2.334454);
print "You have $dosh dollars to spend";
A particular use of sprintf() is to write formatted data to a file. You can call sprintf() and assign its return value to a
variable that can then be printed to a file with fputs().
…………………………………………………………….
2. Investigating Strings with PHP
A string is a collection of characters. String is one of the data types supported by PHP.The string variables can contain
alphanumeric characters. Strings are created when;
• You declare variable and assign string characters to it
• You can directly use them with echo statement.
• String are language construct, it helps capture words.
• Learning how strings work in PHP and how to manipulate them will make you a very effective and productive
developer.
1. Finding the Length of a String with strlen()
You can use strlen() to determine the length of a string. strlen() requires a string and returns an integer representing
the number of characters in the variable you have passed it.
Example:
if (strlen($membership) == 4) {
print "Thank you!";
} else {
print "Your membership number must have 4 digits<P>";
12 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
2. Finding a Substring Within a String with strstr()
You can use strstr() to test whether a string exists embedded within another string. strstr() requires two arguments:
a source string and the substring you want to find within it. The function returns false if the substring is absent.
Otherwise, it returns the portion of the source string beginning with the substring.
Example:
$membership = "pAB7";
if (strstr($membership, "AB")) {
print "Thank you. Don't forget that your membership expires soon!";
} else {
print "Thank you!";
3. Finding the Position of a Substring with strpos()
The strpos() function tells you both whether a string exists within a larger string and where it is to be found. strpos()
requires two arguments: the source string and the substring you are seeking. The function also accepts an optional
third argument, an integer representing the index from which you want to start searching. If the substring does not
exist, strpos() returns false; otherwise, it returns the index at which the substring begins.
$membership = "mz00xyz";
if (strpos($membership, "mz") === 0) {
print "hello mz";
}
4. Extracting Part of a String with substr()
The substr() function returns a portion of a string based on the start index and length of the portion you are looking for.
This function demands two arguments: a source string and the starting index. It returns all characters from the starting
index to the end of the string you are searching.
$test = "scallywag";
print substr($test,6); // prints "wag"
print substr($test,6,2) // prints "wa"
5. Tokenizing a String with strtok()
You can parse a string word by word using strtok(). The strtok() function initially requires two arguments: the string to
be tokenized and the delimiters by which to split the string. The delimiter string can include as many characters as you
want, and the function will return the first token found. After strtok() has been called for the first time, the source
string will be cached. For subsequent calls, you should pass strtok() only the delimiter string. The function will return
the next found token every time it is called, returning false when the end of the string is reached. strtok() will usually be
called repeatedly within a loop.
13 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
<html>
<head>
<title>Listing 13.3 Dividing a string into tokens with strtok()</title>
</head>
<body>
<?php
$test = "http://www.deja.com/qs.xp?";
$test .= "OP=dnquery.xp&ST=MS&DBS=2&QRY=developer+php";
$delims = "?&";
$word = strtok($test, $delims);
while (is_string($word)) {
if ($word) {
print "$word<br>";
}
$word = strtok($delims);
}
?>
</body>
</html>
…………………………………..
3. Manipulating Strings with PHP
A PHP String is a sequence of characters i.e., used to store and manipulate text. PHP provides a rich set of functions to
manipulate string. The following are some of such functions.
a) Cleaning Up a String with trim(), ltrim(), rtrim(), and strip_tags()
The functions trim(), ltrim(), rtrim() are used to remove white spaces from a string.
trim():- removes all spaces in a string.
ltrim():- removes spaces at the beginning of string
rtrim():-removes spaces at the end of string
strip_tags():- used to escape(strip) without applying HTML and PHP tags to string
Example:
<?php
$str=”<b> PHP web development</b>”;
each trim($str);
each ltrim($str);
each rtrim($str);
each strip_tags ($str);
?>
14 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
b) Replacing a Portion of a String Using substr_replace()
The substr_replace() function works similarly to the substr() function, except it enables you to replace the portion of
the string that you extract. The function requires three arguments: the string to transform, the text to add to it, and the
starting index; it also accepts an optional length argument. The substr_replace() function finds the portion of a string
specified by the starting index and length arguments, replaces this portion with the string provided, and returns the
entire transformed string.
Example:
The following code fragment for renewing a user’s membership number changes its second two characters:
<?php
$membership = “mz11xyz”;
$membership = substr_replace($membership, “12”, 2, 2);
echo “New membership number: $membership”;
// prints “New membership number: mz12xyz”
?>
Output:
New membership number: mz12xyz
c) Converting Case
• To get an uppercase version of a string, use the strtoupper () function.
• To convert a string to lowercase characters, use the strtolower () function.
• The ucwords () function makes the first letter of every word in a string uppercase
<?php
$membership = “mz11xyz”;
$membership = strtoupper ($membership);
echo “$membership”; // prints “MZ11XYZ”
$membership1 = strtolower ($membership);
echo “$membership1”; // prints “mz11xyz”
$full_name = “violet elizabeth bott”;
$full_name = ucwords($full_name);
echo $full_name; // prints “Violet Elizabeth Bott”
?>
15 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
d) Wrapping Text with wordwrap () and nl2br ():
When you present plaintext within a web page, you are often faced with a problem in which new lines are not
displayed and your text runs together into one big mess. The nl2br() function conveniently converts every new line into
an HTML break. So
<?php
$string = “one line\n”;
$string .= “another line\n”;
$string .= “a third for luck\n”;
echo nl2br($string);
?>
Output:
one line<br />
another line<br />
a third for luck<br />
If you might want to add arbitrary line breaks to format a column of text. The wordwrap () function is perfect for this.
<?php
$string = “Given a long line, wordwrap() is useful as a means of “;
$string .= “breaking it into a column and thereby making it easier to read”;
echo wordwrap($string);
?>
Output:
Given a long line, wordwrap() is useful as a means of breaking it into a
column and thereby making it easier to read
e) Breaking Strings into Arrays with explode ()
The explode () breaks up a string into an array, which you can then store, sort, or examine as you want. The explode ()
function requires two arguments: the delimiter string that you want to use to break up the source string and the source
string itself.
Example:
…………………………………………………
16 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)
4. Using 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.
Time () : Returns the current time as a Unix timestamp.
date () :- Formats a local date and time.
mktime() :- Returns the Unix timestamp for a date.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo date("l") . "<br>";
echo date("l jS \of F Y h:i:s A") . "<br>";
echo "Oct 3,1975 was on a ".date("l", mktime(0,0,0,10,3,1975)) . "<br>";
echo date(DATE_RFC822) . "<br>";
echo date(DATE_ATOM,mktime(0,0,0,10,3,1975));
?>
</body>
</html>
Output:
Saturday
Saturday 12th of January 2019 11:53:38 PM
Oct 3,1975 was on a Friday
Sat, 12 Jan 19 23:53:38 -0500
1975-10-03T00:00:00-04:00
&&&&&&&&&&&&&&&&&&
Questions:
1. Discuss about date and time functions in PHP.
2. Discuss about Formatting Strings with PHP.
3. Discuss about Investigating Strings with PHP.
4. Discuss about Manipulating Strings with PHP.
17 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)