Professional Documents
Culture Documents
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.
Array
Arrays in PHP is a type of data structure that allows us to store multiple
elements of similar data type under a single variable thereby saving us the effort of
creating a different variable for every data. The arrays are helpful to create a list of
elements of similar types, which can be accessed using their index or key. Suppose
we want to store five names and print them accordingly. This can be easily done by
the use of five different string variables. But if instead of five, the number rises to a
hundred, then it would be really difficult for the user or developer to create so many
different variables. Here array comes into play and helps us to store every element
within a single variable and also allows easy access using an index or a key.
Creating Arrays
An array is created using an array() function in PHP. here are basically three types
of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index where values are
stored linearly.
Associative Arrays: An array with a string index where instead of linear storage,
each value can be assigned a specific key.
Multidimensional Arrays: An array which contains single or multiple array within
it and can be accessed via multiple indices.
Indexed or Numeric Arrays
These type of arrays can be used to store any type of elements, but an index is
always a number. By default, the index starts at zero. These arrays can be created in two
different ways as shown in the following example:
<?php
// One way to create an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
// Second way to create an indexed array
$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";
// Accessing the elements directly
echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";
?>
Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage,
every value can be assigned with a user-defined key of string type.
Example:
<?php
// One way to create an associative array
$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",
"Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");
// Second way to create an associative array
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";
// Accessing the elements directly
echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";
?>
Output:
Accessing the elements directly:
zara
sara
any
Rani
Ravina
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index
instead of a single element. In other words, we can define multi-dimensional arrays as an
array of arrays. As the name suggests, every element in this array can be an array and they
can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can
be accessed using multiple dimensions.
Example:
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "davepunk@gmail.com",
),
array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "montysmith@gmail.com",
),
array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "johnflinch@gmail.com",
)
);
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];
?>
Output:
Dave Punk email-id is: davepunk@gmail.com
John Flinch mobile number is: 9875147536
Traversing Arrays
We can traverse an array using loops in PHP. We can loop through the array in two
ways. First by using for loop and secondly by using foreach.
Example for traversing Indexed array
<?php
// Creating an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// One way of Looping through an array usign foreach
echo "Looping using foreach: \n";
foreach ($name_one as $val){
echo $val. "\n";
}
// count() function is used to count
// the number of elements in an array
$round = count($name_one);
echo "\nThe number of elements are $round \n";
// Another way to loop through the array using for
echo "Looping using for: \n";
for($n = 0; $n < $round; $n++){
echo $name_one[$n], "\n";
}
?>
Output:
Looping using foreach:
Zack
Anthony
Ram
Salim
Raghav
Example:
foreach
($charac
ters as
$c)
{ while
(list($k,
$v) =
each
($c))
{ echo
“$k ...
$v
<br/>”;
}
echo “<hr/>”;
}
8. array_shift()—This function removes (and returns) the first element of an existing array.
Example: $first_element = array_shift($existingArray);
9. array_merge()—This function combines two or more existing arrays.
10. array_keys()—This function returns an array containing all the key names within a
given array.
11. array_values()—This function returns an array containing all the values within a given
array.
12. shuffle()—This function randomizes the elements of a given array. The syntax of this
function is simply as follows: shuffle($existingArray)
13. Sort()--Elements will be arranged from lowest to highest when this function has
completed.
sort( $array [, $sort_flags] );
Output
Array (
[0] => banana
[1] => lemon
[2] => orange
)
Working with objects
Object Oriented Concepts
Before we go in detail, lets define important terms related to Object Oriented Programming.
Class − This is a programmer-defined data type, which includes local functions as
well as local data. You can think of a class as a template for making many instances
of the same kind (or class) of object.
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.
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.
Member function − These are the function defined inside a class and are used to
access object data.
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.
Parent class − A class that is inherited from by another class. This is also called a
base class or super class.
Child Class − A class that inherits from another class. This is also called a subclass
or derived class.
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 take
different number of arguments and can do different task.
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.
Data Abstraction − Any representation of data in which the implementation details
are hidden (abstracted).
Encapsulation − refers to a concept where we encapsulate all the data and member
functions together to form an object.
Constructor − refers to a special type of function which will be called automatically
whenever there is an object formation from a class.
Destructor − refers to a special type of function which will be called automatically
whenever an object is deleted or goes out of scope.
Defining PHP Classes
The general form for defining a new class in PHP is as follows −
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
Once you defined your class, then you can create as many objects as you like of that class
type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Here we have created three objects and these objects are independent of each other and they
will have their existence separately. Next we will see how to access member function and
process member variables.
Calling Member Functions
After creating your objects, you will be able to call member functions related to that object.
One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member
functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example −
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce the following result −
Physics for High School
Advanced Chemistry
Algebra
10
15
7
Example:
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price."<br>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title."<br>" ;
}
}
/* Creating New object using "new" operator */
$maths = new Books;
/* Setting title and prices for the object */
$maths->setTitle( "Algebra" );
$maths->setPrice( 7 );
/* Calling Member Functions */
$maths->getTitle();
$maths->getPrice();
?>
Inheritance
Inheritance is an important principle of object oriented programming methodology. Using
this principle, relation between two classes can be defined. PHP supports inheritance in its
object model.
PHP uses extends keyword to establish relationship between two classes.
Syntax
class B extends A
where A is the base class (also called parent called) and B is called a subclass or child class.
Child class inherits public and protected methods of parent class. Child class may redefine or
override any of inherited methods. If not, inherited methods will retain their functionality as
defined in parent class, when used with object of child class.
Definition of parent class must precede child class definition. In this case, definition of A
class should appear before definition of class B in the script.
Example
<?php
class A{
//properties, constants and methods of class A
}
class B extends A{
//public and protected methods inherited
}
?>
If autoloading is enabled, definition of parent class is obtained by loading the class script.
Types of inheritance
PHP supports three types of inheritances
1) Single inheritance
2) Multi-level inheritance
3) Hierarchial inheritance
Single Inheritance:-Inheritance is the process of get or inherit all properties and methods
of one class to another class.A child class derived from a single parent class is called
single inheritance.
Example:-
Car is derived from vehicle.
Syntax:-
class base{
//properties
//methods
}
class derived extends base{
//properties
//methods
}
Example:-
class vehicle{
public function name($string){
echo "Parent class".$string;
}
}
class car extends vehicle{
public function name($string){
echo "Child class".$string;
}
}
$vehicle=new vehicle();
$car=new car();
$vehicle->name('of vehicle');
$car->name('of car');
Multilevel Inheritance:-Inheritance is the process of get or inherit all properties and
methods of one class to another class.Multilevel means parent inherit property of grand
parent class, grand child inherit property of parent class.
Syntax:-
class grandParent{
//properties
//methods
}
class parent extends grandParent{
//properties
//methods
}
class child extends parent{
//properties
//methods
}
Example:-
class grandFather{
public function gfAge(){
return "Age is 70";
}
}
class Father extends grandFather{
public function fAge(){
return "Age is 50";
}
}
class Son extends Father{
public function sAge(){
return "Age is 20";
}
public function myHistory(){
echo "My grand father".parent::gfAge();
echo "My father".parent::fAge();
echo "My ".$this->fAge();
}
}
$son=new Son();
$son->myHistory();
Output:-
My grand father Age is 70
My father Age is 50
My Age is 20
Hierarchical Inheritance :
Hierarchical inheritance consists of a single parent class and that parent class is
inherited by multiple child class. For Example, there is a parent class named Person and we
have two child class named Employee and Student. Both these class inherit Person class. This
type of the relationship comes from hierarchical inheritance.
Example
<?php
class ParentClass {
var $var = "This is first var";
public $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child_1 extends ParentClass {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo $this->fist_name;
}
}
class child_2 extends ParentClass {
function setVal($set_this){
$this->fist_name = $set_this." - ".$set_this;;
}
function getVal(){
echo $this->fist_name;
}
}
$obj1 = new child_1();
$obj1->setVal("This is first child class");
$obj1->getVal();
echo "<br/><br/>";
$obj2 = new child_2();
$obj2->setVal("This is second child class");
$obj2->getVal();
?>
Output:
This is first child class
This is second child class- This is second child class
We have one parent class named ParentClass and two child class child_1 and child_2
respectively. The given scenario of the inheritance is called Hierarchical Inheritance.
Example,
%.5f // Defines Real Number Precision.
%.2s // Maximum Character to be allowed in a string.
A type specifier that says what type the argument data should be treated as.
Here are the possible type specifiers:
% A literal percent character. No argument is required.
c The argument is treated as an integer, and presented as the character with that ASCII
value.
Example
<?php
// PHP program to illustrate Working
// of different Format Specifiers
// Creating Dummy Variables
$numValue = 5;
$strValue = "GeeksForGeeks";
// Using Sign Specifier.
printf("Signed Number: %+d\n",$numValue);
// Padding and Width Specifier.
printf("Padding and Width\n%'03d\n%'03d\n",
$numValue,$numValue+10);
// Precision Specifier.
printf("Precision: %.5f %.5s\n", $numValue, $strValue);
// Different DataTypes.
// Integer and Percentile.
printf("Percentage: %d%%\n",$numValue);
// Binary Octal and Hexadecimal Representation.
printf("Binary: %b Octal: %o Hexadecimal: %x\n",
$numValue+10,$numValue+10,$numValue+10);
// Character Representation.
printf("Character: %c\n",$numValue+60);
// Strings.
printf("String: %s\n",$strValue);
// Real Numbers.
printf("RealNumber: %f\n",1/$numValue);
// Scientific Numerical Representation.
printf("Scientific Representation:%e\n",$numValue+100);
?>
Output:
Signed Number: +5
Padding and Width
005
015
Precision: 5.00000 Geeks
Percentage: 5%
Binary: 1111 Octal: 17 Hexadecimal: f
Character: A
String: GeeksForGeeks
RealNumber: 0.200000
Scientific Representation:1.050000e+2
Investigating Strings in 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 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:
<?php
if (strlen($membership) == 4) {
echo "<p>Thank you!</p>";
} else {
echo "<p>Your membership number must have 4 digits.</p>";
}
?>
Finding a Substring Within a String with strstr()
You can use the strstr() function to test whether a string exists within another string. This
function requires two arguments: the source string and the substring you want to find within
it. The function returns false if the substring cannot be found; otherwise, it returns the
portion of the source string, beginning with the substring. For the following example,
imagine that we want to treat membership codes that contain the string AB differently from
those that do not:
<?php
$membership = "pAB7";
if (strstr($membership, "AB")) {
echo "<p>Your membership expires soon!</p>";
} else {
echo "<p>Thank you!</p>";
}
?>
Because the value of the $membership variable contains the substring AB,
the strstr() function returns the string AB7. The function resolves to true when tested, so we
print the appropriate message, "Your membership expires soon!". But what happens if we
search for "pab7"? Because strstr() is case sensitive, AB will not be found. The if statement's
original test will fail, and the default message will be printed to the browser ("Thank you!").
If we want search for either AB or ab within the string, we must use strstr() in place
of substr(); the function is used in exactly the same way, but its search is not case sensitive.
Notice the trick we had to play to get expected results. While the strpos() function
finds mz in our string, it finds it at the first element the 0 position. Returning zero will
resolve to false in our if condition test. To work around this, we use the equivalence
operator ===, which returns TRue if the left- and right-hand operands are equivalent and of
the same type, as they are in this case.
Extracting Part of a String with substr()
The substr() function returns a string based on the start index and length of the characters
you are looking for. This function requires two arguments: a source string and the starting
index. Using these arguments, it will return all the characters from the starting index to the
end of the string you are searching. You can also (optionally) provide a third argumentan
integer representing the length of the string you want returned. If this third argument is
present, substr() returns only that number of characters, from the start index onward.
<?php
$test = "phpcoder";
echo substr($test,3)."<br>"; // prints "coder"
echo substr($test,3,2)."<br>" // prints "co"
?>
If you pass substr() a negative number as its second (starting index) argument, it will count
from the end rather than the beginning of the string. The following fragment writes a
specific message to people who have submitted an email address ending in .fr:
<?php
$test = "pierre@wanadoo.fr";
if ($test = substr($test, -3) == ".fr") {
echo "<p>Bonjour! Nous avons des prix spéciaux de vous.</p>";
} else {
echo "<p>Welcome to our store.</p>";
}
?>
Manipulating Strings