Unit-II: 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.
Q) What Are Arrays? Explain how to create an Array. (OR) Explain
different types of Arrays.
An
array is a data structure that stores one or more similar type of values in a
single variable . Arrays are indexed, which means that each entry is made up of
a key and a value. The key is the index position, beginning with 0 and
increasing incrementally by 1 with each new element in the array. The value can be a string, an integer, or
whatever we gave to it.
An
array can be created using either the array
( ) function or the array operator
[].
Eg:
1.
$rainbow = array(“red”,
“orange”, “yellow”, “green”, “blue”, “indigo”, “violet”);
2.
$rainbow[ ] = “red”;
$rainbow[ ] = “orange”;
$rainbow[ ] = “yellow”;
$rainbow[ ] = “green”;
$rainbow[ ] = “blue”;
$rainbow[ ] = “indigo”;
$rainbow[ ] = “violet”;
Both
create a seven-element array called $rainbow, with values starting at index position 0 and
ending at index position 6.
In PHP, there are three types of arrays:
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
1. Indexed
Arrays: Indexed arrays use an index position as the key—0, 1, 2, and so forth
Syntax: array(value1,value2,value3,etc.);
Example:
$rainbow = array(“red”,
“orange”, “yellow”, “green”, “blue”,
“indigo”, “violet”);
2. Associative
arrays: Arrays
with named keys.
Synt ax: array(key=>value, key=>value, key=>value,
etc.);
Example:
$character = array(“name”
=> “Bob”,“occupation”
=> “superhero”, “age” => 30,“special power” => “x-ray vision”);
The four keys in the $character
array are name, occupation, age, and special power. The associated values are
Bob, superhero, 30, and x-ray vision, respectively.
3. Multidimensional
array: 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.
Example:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Q) Write Some Array-Related Functions.
1. count(
)-This functions counts the
number of elements in an array.
Example: $colors
= array(“blue”, “black”, “red”,
“green”);
count($colors); return a value of 4.
count($colors); return a value of 4.
2. 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”);
3. array_
pop()—This function removes (and returns) the last
element of an existing array
Example: $last_element = array_pop($existingArray);
4. 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”);
5. array_shift()—This
function removes (and returns) the first
element of an existing array
Example:
$first_element =
array_shift($existingArray);
6. array_merge()—This
function combines two or more existing arrays.
Example:
$newArray = array_merge($array1,
$array2);
7. array_keys()—This
function returns an array containing all
the key names within a given
array.
Example:
$keysArray = array_keys($existingArray);
8. array_values()—This
function returns an array containing all
the values within a given array.
Example:
$valuesArray =
array_values($existingArray);
9. shuffle()—This
function randomizes the elements of a
given array.
Example:
shuffle($existingArray);
10.
sort($arr):
This function sorts the elements of an array in ascending order. String values
will be arranged in ascending alphabetical order.
Example: $data =
array("g", "t", "a", "s");
sort($data);
Q) Explain Concept of Object Oriented Programming in PHP
Object Oriented is an approach to software development that models
application around real world objects such as employees, cars, bank accounts,
etc.
1. Class
− A class defines the properties and methods of a real world object.
2. Object
− An individual instance of the data structure defined by a class.
a. 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.
b. Member
function − these are the function defined inside a
class and are used to access object data.
3. Inheritance
– The
inheritance is a way to form new classes using classes that have already been
defined. The newly formed classes are called derived
classes, the classes that we derive from are called base classes. Important benefits of inheritance are
code reuse and reduction of complexity of a program. The derived classes
(descendants) override or extend the functionality of base classes (ancestors).
4. 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 make take
different number of arguments and can do different task.
5. Overloading
− a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments.
6. Data
Abstraction − Any representation of data in which the
implementation details are hidden (abstracted).
7. Encapsulation
− refers to a concept where we encapsulate all the data and member functions
together to form an object.
8. Constructor
− refers to a special type of function which will be called automatically
whenever there is an object formation from a class.
9. Destructor
− refers to a special type of function which will be called automatically
whenever an object is deleted or goes out of scope
Q) Explain how to create an Objects and Class
in PHP and how to access properties and methods in PHP
Objects
are basic building blocks of a PHP OOP program. An object is a combination of
data and methods. In a OOP program, we create objects. These objects
communicate together through methods. Each object can receive messages, send
messages, and process data. There are two steps in creating an object. First, we create a class. A class is a template for an object. It is a blueprint which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.
1.
A class can be declared using
the class keyword, followed by the name of the class and a pair of curly braces
({}), A class definition includes the class name and the properties and methods
of the class. Class names are case-insensitive and must conform to the rules
for PHP identifiers.
Syntax
for a class definition:
class classname [ extends baseclass ]
{
[ var $property [ = value ]; ... ]
[ function functionname (args) {
// code
}
...
]
}
2.
Once a class has been defined, objects
can be created from the class with the new keyword.
$object = new Class;
Example: $rasmus =
new Person;
Some
classes permit to pass arguments to the new call.
Example:
$object = new Person('Fred', 35);
3. Accessing Properties
and Methods
The variables declared inside an
object are called properties.Once an object is created,we can use the ->
notation to access methods and properties of the object:
$object->methodname([arg,
... ])
For
example:
printf("Rasmus
is %d years old.\n", $rasmus->age);
// property access
$rasmus->birthday(); // method call
$rasmus->set_age(21); // method call
with arguments
Methods
are functions, so they can take arguments and return a value:
$clan
= $rasmus->family('extended')
<?php
class Rectangle
{
public $length = 0;
public $width = 0;
public function getPerimeter(){
return (2 * ($this->length + $this->width));
}
public function getArea(){
return ($this->length * $this->width);
}
}
?>
Save the above file
as Rectangle.php
<?php
require "Rectangle.php";
$obj = new Rectangle;
echo $obj->length . "<br>";
echo $obj->width . "<br>";
$obj->length = 30;
$obj->width = 20;
echo $obj->length . "<br>";
echo $obj->width . "<br>";
echo $obj->getPerimeter() .
"<br>";
echo $obj->getArea() .
"<br>";
?>
Q)
Write a note on Constructors and Destructors.
Constructor: A constructor is a special kind of a method. It is
automatically called when the object is created. The purpose of the constructor
is to initiate the state of the object. The name of the constructor in PHP is
__construct()
(with two underscores).
Destructor: The magic method __destruct() (known as
destructor) is executed automatically when the object is destroyed. A
destructor function cleans up any resources allocated to an object once the
object is destroyed.
Example:
<?php
class MyClass
{
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}
$obj = new MyClass;
echo
"The end of the file is reached.<br>";
?>
Q)
Explain Object Inheritance.
Inheritance: The inheritance is a way to form new classes using classes that
have already been defined. The newly formed classes are called derived
classes, the classes that we derive from are called base classes.
Important benefits of inheritance are code reuse and reduction of complexity of
a program. The derived classes (descendants) override or extend the
functionality of base classes (ancestors).
Example:
<?php
class
Base {
function __construct() {
echo "Construction of Base class
\n";
}
}
class
Derived extends Base {
function __construct() {
parent::__construct();
echo "Construction of Derived
class \n";
}
}
$obj1
= new Base();
$obj2
= new Derived();
?>
String: A string is a sequence of letters, numbers,
special characters and arithmetic values or combination of all. The simplest
way to create a string is to enclose the string literal (i.e. string
characters) in single quotation marks (').
Double quotation
marks (")also use to declare strings. However, single and double quotation
marks work in different ways. Strings enclosed in single-quotes are treated
almost literally, whereas the strings delimited by the double quotes replaces
variables with the string representations of their values as well as specially
interpreting certain escape sequences.
Formatting Strings:
1. escape-sequence characters:
·
\n is replaced by the
newline character
·
\r is replaced by the
carriage-return character
·
\t is replaced by the tab
character
·
\$ is replaced by the
dollar sign itself ($)
·
\" is replaced by a
single double-quote (")
·
\\ is replaced by a
single backslash (\)
Example:
<?php
$my_str = 'World';
echo "Hello,
$my_str!<br>"; //
Displays: Hello World!
echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
echo '<pre>Hello\tWorld!</pre>';
// Displays: Hello\tWorld!
echo
"<pre>Hello\tWorld!</pre>"; // Displays: Hello World!
echo 'I\'ll be back'; // Displays: I'll be back
?>
2. printf(): The printf()
function requires a string argument, known as a format control string. It also
accepts additional arguments of different types. The different types of
formatting strings of PHP are as shown below.
printf(:formatting
control strings”,var1,var2…);
FORMAT
SPECIFIERS:
|
%b
|
binary
|
|
|
%c
|
ASCII character
|
|
|
%d
|
signed decimal number
|
|
|
%e
|
scientific number
|
|
|
%u
|
unsigned decimal number
|
|
|
%f
|
float with local settings
|
|
|
%F
|
float without local settings
|
|
|
%o
|
octal number
|
|
|
%x
|
lowercase hexadecimal
|
|
|
%X
|
uppercase hexadecimal
|
|
Example:
<?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);
?>
3. padding specifier:
The string can be padded by leading characters. The
padding specifier should directly follow the percent sign that begins a conversion
specification
<?php
printf("%04d", 36);
// prints "0036"
?>
4.
Field Width: A field width specifier is an integer that should be placed after the
percent sign that begins a conversion
specification.
Example:
<?php
printf(“%20s\n”, “Books”);
printf(“%20s\n”, “CDs”);
printf(“%20s\n”, “DVDs”);
printf(“%20s\n”, “Games”);
printf(“%20s\n”, “Magazines”);
?>
Q) How to Investigating Strings
in PHP?
1. Indexing Strings:
A string as an array of characters, and thus strings can be access
with the individual characters.
Example:
<?php
$test = “phpcoder”;
echo $test[0]; // prints “p”
echo $test[4]; // prints “o”
?>
2. strlen():The strlen() function is used to
calculate the number of characters inside a string. This function requires a
string as its argument and returns an integer representing the number of
characters in the string.
Example:
<?php
$membership = “pAB7”;
if (strlen($membership) == 4) {
echo “<p>Thank you!</p>”;
} else {
echo “<p>Your membership number must be four characters long.</p>”;
}
?>
3. strstr():the strstr() function is used to test whether a string exists within another string or not. This function
requires two arguments: the source
string and the substring to find within it. The function returns false if it
cannot find the substring; otherwise, it returns the portion of the source string, beginning with the
substring.
Example:
<?php
$membership = “pAB7”;
if (strstr($membership, “AB”)) {
echo “<p>Your membership expires soon!</p>”;
} else {
echo “<p>Thank you!</p>”;
}
?>
4. strpos(): The strpos() function is used
to tells whether a string exists within a larger string as well as where it is
found. The strpos() function requires two arguments: the source string and the substring to
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.
Example:
<?php
$membership = “mz00xyz”;
if (strpos($membership, “mz”) === 0) {
echo “Hello mz!”;
}
?>
5. substr(): The substr() function returns a
string based on the start index and length of the characters.
This function requires two arguments: a source string and the starting index.
Using these arguments, the function returns all the
characters from the
starting index to the end of the
string. It also (optionally) provide a third argument—an integer
representing the length of the string to returned. If this third argument is
present, substr( ) returns only that number of characters, from the
start index onward:
Example:
<?php
$test = “phpcoder”;
echo substr($test,3).”<br/>”; // prints “coder”
echo substr($test,3,2).”<br/>”; // prints “co”
?>
Q) How to Manipulating Strings
with PHP
PHP provides many built-in functions for manipulating strings like calculating
the length of a string, find substrings or characters, replacing part of a
string with different characters, take a string apart, and many others.
1. The trim()
function shaves any whitespace characters, including newlines, tabs, and
spaces, from both the start and end
of a string.
2. The
str_word_count() function counts the number of words in a string
3. The
str_replace() replaces all occurrences of the search text within the target
string.
4. The strrev()
function reverses a string.
5. The strpos()
function is used to search for a string or character within a string.
6. The
strtoupper() function converts string into upper case.
7. The
Strtolower( ) function converts string to lowercase characters.
8. The ucwords()
function makes the first letter of
every word in a string into uppercase
9. the ucfirst() function capitalizes only the
first letter in a string.
Some examples:
example:
<?php
$text = “\t\tlots
of room to breathe “;
echo “<pre>$text</pre>”;
// prints “
lots of room to breathe “;
$text = trim($text);
echo
“<pre>$text</pre>”;
// prints “lots of
room to breathe”;
?>
Example:
<?php
$membership = “mz11xyz”;
$membership = substr_replace($membership, “12”, 2, 2);
echo “New membership number:
$membership”;
// prints “New membership number:
mz12xyz”
?>
Q) Explain Using Date and Time Functions in PHP.
1. time():
time() function gives information about the current date and time.
syntax:
echo time();
TimeStamp: A Unix Timestamp is the number of seconds that
have passed since January 1, January, 1970 00:00:00 Greenwich Mean Time (GMT).
Currently, the timestamp is 1513422833, but since it changes every second, the
number will increase if you refresh the page
Example:
<?php
echo time();
// sample
output: 1326853185
// this represents January 17, 2012 at 09:19PM
?>
2.The PHP Date() Function: The date() function accepts two arguments. The
first argument is the format that you want the timestamp in. The second
argument (optional) is the timestamp that you want formatted. If no timestamp
is supplied, the current timestamp will be used.
Syntax:
<?php
date(format,[timestamp]);
?>
PHP provides over thirty-five case-sensitive characters that are used
to format the date and time. These characters are:
|
|
Character
|
Description
|
Example
|
|
Day
|
J
|
Day of the Month, No Leading Zeros
|
1 - 31
|
|
Day
|
D
|
Day of the Month, 2 Digits, Leading Zeros
|
01 - 31
|
|
Day
|
D
|
Day of the Week, First 3 Letters
|
Mon - Sun
|
|
Day
|
l (lowercase 'L')
|
Day of the Week
|
Sunday - Saturday
|
|
Day
|
N
|
Numeric Day of the Week
|
1 (Monday) - 7 (Sunday)
|
|
Day
|
W
|
Numeric Day of the Week
|
0 (Sunday) - 6 (Saturday)
|
|
Day
|
S
|
English Suffix For Day of the Month
|
st, nd, rd or th
|
|
Day
|
Z
|
Day of the Year
|
0 - 365
|
|
Week
|
W
|
Numeric Week of the Year (Weeks Start on Mon.)
|
1 - 52
|
|
Month
|
M
|
Textual Representation of a Month, Three Letters
|
Jan - Dec
|
|
Month
|
F
|
Full Textual Representation of a Month
|
January - December
|
|
Month
|
M
|
Numeric Month, With Leading Zeros
|
01 - 12
|
|
Month
|
N
|
Numeric Month, Without Leading Zeros
|
1 - 12
|
|
Month
|
T
|
Number of Days in the Given Month
|
28 - 31
|
|
Year
|
L
|
Whether It's a Leap Year
|
Leap Year: 1, Otherwise: 0
|
|
Year
|
Y
|
Numeric Representation of a Year, 4 Digits
|
1999, 2003, etc.
|
|
Year
|
Y
|
2 Digit Representation of a Year
|
99, 03, etc.
|
|
Time
|
A
|
Lowercase Ante Meridiem & Post Meridiem
|
am or pm
|
|
Time
|
A
|
Uppercase Ante Meridiem & Post Meridiem
|
AM or PM
|
|
Time
|
B
|
Swatch Internet Time
|
000 - 999
|
|
Time
|
G
|
12-Hour Format Without Leading Zeros
|
1 - 12
|
|
Time
|
G
|
24-Hour Format Without Leading Zeros
|
0 - 23
|
|
Time
|
H
|
12-Hour Format With Leading Zeros
|
01 - 12
|
|
Time
|
H
|
24-Hour Format With Leading Zeros
|
00 - 23
|
|
Time
|
I
|
Minutes With Leading Zeros
|
00 - 59
|
|
Time
|
S
|
Seconds With Leading Zeros
|
00 - 59
|
|
Timezone
|
E
|
Timezone Identifier
|
Example: UTC, Atlantic
|
|
Timezone
|
I (capital i)
|
Whether Date Is In Daylight Saving Time
|
1 if DST, otherwise 0
|
|
Timezone
|
O
|
Difference to Greenwich Time In Hours
|
Example: +0200
|
|
Timezone
|
P
|
Difference to Greenwich Time, With Colon
|
Example: +02:00
|
|
Timezone
|
T
|
Timezone Abbreviation
|
Examples: EST, MDT ...
|
|
Timezone
|
Z
|
Timezone Offset In Seconds
|
-43200 through 50400
|
Using a combination of these characters and commas, periods, dashes,
semicolons and backslashes, you can now format dates and times.
<?php
// Will Echo: 3:13 AM Saturday, December 16, 2017
echo date("g:i A l, F d, Y");
// Will Echo: 2017-12-15
$yesterday = strtotime("yesterday");
echo date("Y-m-d", $yesterday);
?>
// Will Echo: 3:13 AM Saturday, December 16, 2017
echo date("g:i A l, F d, Y");
// Will Echo: 2017-12-15
$yesterday = strtotime("yesterday");
echo date("Y-m-d", $yesterday);
?>
3. The
PHP Strtotime() Function: The
strtotime() function accepts an English datetime description and turns it into
a timestamp.
Some examples are:
<?php
echo strtotime("now") . "<br />";
echo strtotime("tomorrow") . "<br />";
echo strtotime("yesterday") . "<br />";
echo strtotime("10 September 2000") . "<br />";
echo strtotime("+1 day") . "<br />";
echo strtotime("+1 week") . "<br />";
echo strtotime("+1 week 2 days 4 hours 2 seconds") . "<br
/>";
echo strtotime("next Thursday") . "<br />";
echo strtotime("last Monday") . "<br />";
echo strtotime("4pm + 2 Hours") . "<br />";
echo strtotime("now + 2 fortnights") . "<br />";
echo strtotime("last Monday") . "<br />";
echo strtotime("2pm yesterday") . "<br />";
echo strtotime("7am 12 days ago") . "<br />";?>
Comments
Post a Comment