You are on page 1of 18

UNIT I

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

The number of elements is 5


Looping using for:
ZACK
ANTHONY
RAM
SALIM
RAGHAV

Some array related functions


The array functions allow you to access and manipulate arrays.Simple and multi-dimensional
arrays are supported.
Installation
The array functions are part of the PHP core. There is no installation needed to use these
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
($charac
ters 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);
9. array_merge()—This function combines two or more existing arrays.

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

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

Example: $keysArray = array_keys($existingArray);

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

Example: $valuesArray = array_values($existingArray);

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

Example for sort() function


<?php
$input = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" );
sort($input);
print_r($input);
?>

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

function myfunc ($arg1, $arg2) {


[..]
}
[..]
}
?>
Here is the description of each line −
 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function
definitions.
 Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a constant
value.
 Function definitions look much like standalone PHP functions but are local to the
class and will be used to set and access object data.
Example
Here is an example which defines a class of Books type −
<?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/>";
}
}
?>
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.

Working with Strings, Dates and Time


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 ('), like this:
$my_string = 'Hello World';
You can also use double quotation marks ("). 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 (\)
Here's an example to clarify the differences between single and double quoted strings:
Example
Run this code »
<?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 Strings
There's a pair of string functions that are particularly useful when you want to format
data for display (such as when you're formatting numbers in string form): printf and sprintf.
The printf function echoes text directly, and you assign the return value of sprintf to a string.
Here's how you use these functions (items in square brackets, [ and ], in function
specifications like this one are optional):

printf (format [, args])


sprintf (format [, args])

 Sign specifier can be used to forcibly display the sign (- or +) to be used on a


number. By default, only the – sign is displayed on negative numbers. Using this
specifier positive numbers are shown with a preceding +. This can be achieved using a +
symbol and can be implemented only upon numeric values. Example,
%+d // Specify the integer along with it's sign (+ or -).
 Padding specifier can be used to specify what character will be used for padding
the results to any defined string size. By default, spaces are used as padding. An
alternate padding character can be specified by prefixing it with a single quote or ‘.
Example,
%'0d // Pad with 0s to achieve the right length.
 Alignment specifier can be used to specify the alignment of the result i.e. whether
left-justified or right-justified. By default it is right-justified. Using a – character makes
it left-justified. Example,
%-s // Specifies the alignment as left-justified.
 Width specifier can be used to specify the minimum number of characters to be
present in the result itself. It can be specified using any number denoting the minimum
width. It is seen in use with padding specifier the most. Example,
// Specifies there should be at least 5 digits,
%'05d // if less, then 0s are filled to get the desired result.
 Precision Specifier can be used to specify the precision while working with real
numbers. A period or ‘.’ followed by an optional decimal digit string that refers to the
decimal digits to be displayed after the decimal.When using this specifier on a string, it
specifies the maximum character limit on the string.

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.

b The argument is treated as an integer, and presented as a binary number.

c The argument is treated as an integer, and presented as the character with that ASCII
value.

d The argument is treated as an integer, and presented as a (signed) decimal number.

u The argument is treated as an integer, and presented as an unsigned decimal number.

f The argument is treated as a float, and presented as a floating-point number.

- The argument is treated as an integer, and presented as an octal number.

s The argument is treated as and presented as a string.

x The argument is treated as an integer and presented as a hexadecimal number (with


lowercase letters).

X The argument is treated as an integer and presented as a hexadecimal number (with


uppercase letters).

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

Finding the Position of a Substring with strpos()


The strpos() function tells you 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
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. The
following fragment uses strpos() to ensure that a string begins with the string mz:
<?php
$membership = "mz00xyz";
if (strpos($membership, "mz") === 0) {
echo "Hello mz!";
}
?>

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

Tokenizing a String with strtok()


You can parse a string word by word using the strtok() function. This function 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
cachedfor subsequent calls, you should only pass the delimiter string to the strtok() function.
The function will return the next found token every time it is called, returning false when the
end of the string is reached. The strtok() function will usually be called repeatedly, within a
loop. The below example uses strtok() to tokenize a URL, splitting the host and path from
the query string, and further dividing the name/value pairs of the query string.
Dividing a String into Tokens with strtok()
1: <?php
2: $test = "http://www.google.com/search?";
3: $test .= "hl=en&ie=UTF-8&q=php+development+books&btnG=Google+Search";
4: $delims = "?&";
5: $word = strtok($test, $delims);
6: while (is_string($word)) {
7: if ($word) {
8: echo "$word<br>";
9: }
10: $word = strtok($delims);
11: }
12: ?>

Manipulating Strings

You might also like