PHP unit2
Q) What Are Arrays? Explain how to create an Array.
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.
Creating Arrays:
An array can be created using
either the array ( ) function or the array operator []. The array ( ) function is
usually used when we create a new array and populate it with more than one
element. The array operator [ ] is often used when we want to create a new array
with just one element at the outset, or when you want to add to an existing
array element.
Creating Array using the
array ( ) function:
$rainbow = array(“red”,
“orange”, “yellow”, “green”, “blue”, “indigo”, “violet”);
Creating Array using the
array operator[ ]:
$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.
Also can specify the index positions as shown below:
$rainbow[0] = “red”;
$rainbow[1] = “orange”;
$rainbow[2] = “yellow”;
$rainbow[3] = “green”;
$rainbow[4] = “blue”;
$rainbow[5] = “indigo”;
$rainbow[6] = “violet”;
Q) Explain how to Create Associative Arrays.
Indexed arrays use an index position as the key—0, 1, 2, and so forth. Associative
arrays use actual named keys.
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. You can
reference specific elements of an associative array using the specific key.
echo
$character[‘occupation’];
output:
superhero
Q) Write a note
on 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
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);
sort($data);
Q) Explain Concept of Object Oriented
Programming in PHP
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.
Concepts of
Object Oriented Programming:
1. Class − This is a
programmer-defined data type, which includes local functions as well as local
data.
2. Object − An individual
instance of the data structure defined by a class. You define a class once and
then make many objects that belong to it. Objects are also known as instance.
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. These variables are called attribute of the
object once an object is created.
b.
Member function − These are the function defined inside a class
and are used to access object data.
3. Inheritance − When a class is
defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and
variables of a parent class.
a.
Parent class − A class that is inherited from by another
class. This is also called a base class or super class.
b.
Child Class − A class that inherits from another class.
This is also called a subclass or derived class.
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. Similarly functions can also be
overloaded with different implementation.
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 Object in PHP and how to access properties and methods
in PHP
It's much easier to create objects and use them than it is to
define object class. To create an object of a given class, use 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);
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')
Q)
How to create objects?
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. Class methods and properties can directly be accessed through this
object instance.
3. 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:
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
To make the object-oriented programming easier,
PHP provides some magic methods that are executed automatically when certain
actions occur within an object.
The magic method __construct() (known as
constructor) is executed automatically whenever a new object is created.
Similarly, 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.
<?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
Classes can inherit the properties and methods
of another class using the extends keyword. This process of
extensibility is called inheritance. It is probably the most powerful reason
behind using the object-oriented programming model.
<?php
require "Rectangle.php";
class Square extends Rectangle
{
public
function isSquare(){
if
($this->length == $this->width){
return true;
}
else{
return false;
}
}
}
$obj = new Square;
$obj->length = 20;
$obj->width = 20;
if($obj->isSquare()){
echo
"The area of the square is ";
} else{
echo
"The area of the rectangle is ";
};
echo $obj->getArea();
?>
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.
The escape-sequence replacements are:
- \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 (\)
<?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
?>
Formatting string using 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.
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);
?>
Formatting string with padding specifier:
The string can be padded by leading characters. The
padding specifier should directly follow the percent sign that begins a conversion
specification. To pad string with
leading zeroes, 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 zeroes:
<?php
printf("%04d", 36);
// prints "0036"
?>
Formatting string
with a 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. 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 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”
?>
Example:
<?php
$string = “<h1>The 2010 Guide to All Things Good in the World</h1>”;
$string .= “<p>Site contents copyright 2010.</p>”;
echo str_replace(“2010”,”2012”,$string);
?>
<?php
$membership = “mz11xyz”;
$membership = strtoupper($membership);
echo “$membership”; // prints “MZ11XYZ”
?>
<?php
$membership = “MZ11XYZ”;
$membership = strtolower($membership);
echo “$membership”; // prints “mz11xyz”
?>
<?php
$full_name = “violet elizabeth
bott”;
$full_name =
ucwords($full_name);
echo $full_name; // prints “Violet Elizabeth Bott”
?>
<?php
$myString = “this is my
string.”;
$myString = ucfirst($myString);
echo $myString; // prints “This is my
string.”
?>
Q) Explain Using Date and Time Functions
in PHP.
|
Function
|
Description
|
|
Returns the
Current Time as a Unix Timestamp
|
|
|
Formats a
Local Time/Date
|
|
|
Parses an
English Textual Date or Time Into a Unix Timestamp
|
1.
time():
time() function gives information about the current date and time.
Example:
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
PHP Date the following basic syntax
<?php
date(format,[timestamp]);
?>
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.
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. It is a simple way to determine "next week" or "last monday" without using the time() function and a bunch of math.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