0% found this document useful (0 votes)
9 views24 pages

PHP and Mysql-II

Uploaded by

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

PHP and Mysql-II

Uploaded by

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

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.
………………………………………………………………………………………………………………………
………………………………………………………………….

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.

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:


The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
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

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 1


<!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)
);

. 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.

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.
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] . ".";
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/>”;
}
V.Sai Krishna M.Sc., M.Tech., (PhD), Page 2
V.Sai Krishna M.Sc., M.Tech., (PhD), Page 3
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.

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”);
array_pop()—This function removes (and returns) the last element of an existing array.

Example: $last_element = array_pop($existingArray);

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”);

array_shift()—This function removes (and returns) the first element of an existing array. Example:
$first_element = array_shift($existingArray);
array_merge()—This function combines two or more existing arrays.

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

array_keys()—This function returns an array containing all the key names within a given array.

Example: $keysArray = array_keys($existingArray);

array_values()—This function returns an array containing all the values within a given array.

Example: $valuesArray = array_values($existingArray);

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.

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 4


V.Sai Krishna M.Sc., M.Tech., (PhD), Page 5
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.

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.
?>

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 6


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();
?>

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 7


2. Object Instance :

When the inheritance and the methods of the parent class are accessed by the child
class, we call the concept . The child class can inherit the parent method and give
own method implementation, this property is called 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

l Inheritance: In Single Level Inheritance the Parent class methods will be extended
by the child class. All s 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();
?>

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 8


MultiLeve Inheritance: In MultiLevel Inheritance, the parent class method will be inherited by child
l and again l inherit the child class method.
subclass
wil

<?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();

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 9


?>
…………………######################.....................
Question
s: out working with objects in PHP out object Inheritance.
Discuss
ab
Discuss
ab

Chapter-III (Working with Strings, Dates and Time)

Syllabus: atting Strings with PHP, Investigating Strings with PHP, Manipulating Strings with PHP,
Form Time Using Date and in PHP.
Functions ………………………………………………………………………………………………………
…………… ………………………………………………………….
…………
ing Strings with PHP
1. Formatt
d sprintf() functions that you can use to format strings in many different ways. These
The printf() functions are handy convert data between different formats — either to make it easy for
an when you people to read, or for passing to
need m.
another
progra many other functions to format strings in specific ways — for example, the date() function
is ideal for e strings. However, printf() and sprintf() are great for general-purpose
PHP formatting.
features
formatting printf()
dat
a string argument, known as a format control string. It also accepts additional arguments
Working with of different at control string contains instructions indicating how to display these additional
arguments.
printf() ippet, for example, uses printf() to output an integer as a decimal: my number: %d", 55);
requires my number: 55"
types. The
form ecification begins with a percent (%) symbol and defines how to treat the corresponding
The argument to include as many conversion specifications as you want within the format
following sn control string, as long as you ent number of arguments to printf().
printf("This
is the other available type Specifier.
// prints
"This is Description

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 10


conversion
sp printf().
You can
send an
equival

Table 13.1
lists

Specifier

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 11


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:

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 12


V.Sai Krishna M.Sc., M.Tech., (PhD), Page 13
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>";

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().

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 14


…………………………………………………………….

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.

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:

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>";

}
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";

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 15


<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);

?>

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.

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 16


V.Sai Krishna M.Sc., M.Tech., (PhD), Page 17
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

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”
?>

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.

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 18


<?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

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:
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:
Discuss about date and time functions in PHP.
Discuss about Formatting Strings with PHP.
Discuss about Investigating Strings with PHP.
Discuss about Manipulating Strings with PHP.

V.Sai Krishna M.Sc., M.Tech., (PhD), Page 19


V.Sai Krishna M.Sc., M.Tech., (PhD), Page 20
V.Sai Krishna M.Sc., M.Tech., (PhD), Page 21
V.Sai Krishna M.Sc., M.Tech., (PhD), Page 22
V.Sai Krishna M.Sc., M.Tech., (PhD), Page 23
V.Sai Krishna M.Sc., M.Tech., (PhD), Page 24

You might also like