Module 2 Php
Module 2 Php
MODULE 2
ARRAY
• An array is a data structure that stores one or more data values having some
relation among them, in a single variable.
• For example, if you want to store the marks of 10 students in a class, then
instead of defining 10 different variables, it’s easy to define an array of 10
length.
• A PHP array can be used to implement different data structures such as a stack,
queue, list (vector), hash table, dictionary, etc.
• The value part of an array element can be other arrays. This fact can be used to
implement tree data structure and multidimensional arrays.
• One is to use the built-in array() function, and the other is to use a shorter
syntax where the array elements are put inside square brackets.
• Creating an array
<?php
$cars = ["Volvo", "BMW", "Toyota"];
var_dump($cars);
?>
• The built-in array() function uses the parameters given to it and returns an object
of array type.
• The association between the key and its value is denoted by the "=>" symbol.
1|Page
MODULE 2 PHP
2|Page
MODULE 2 PHP
• In PHP, an indexed array may be created using the array() function or the
square bracket syntax.
• In this type of array, each value is identified by its associated key and not an
index.
• Associative arrays are used to implement data structures such as dictionary,
maps, trees, etc.
• In PHP, the "=>" symbol is used to establish association between a key and its
value.
• Both the approaches of declaring an array – the array() function and the square
bracket notation – can be used.
3|Page
MODULE 2 PHP
4|Page
MODULE 2 PHP
PHP Array Functions allow to interact with and manipulate arrays in various ways.
PHP arrays are essential for storing, managing, and operating on sets of variables.
PHP supports simple and multi-dimensional arrays and may be either user created
or created by another function.
Function Description
5|Page
MODULE 2 PHP
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "va
array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, u
user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a
defined key comparison function)
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
6|Page
MODULE 2 PHP
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, usin
defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a
use key comparison function)
array_map() Sends each value of an array to a usermade function, which returns new
The PHP string functions are part of the PHP core. No installation is required to use
these functions.
strrpos() Finds the position of the last occurrence of a string inside another string
(casesensitiv
strspn() Returns the number of characters found in a string that contains only characters
from specified charlist
strstr() Finds the first occurrence of a string inside another string (case-sensitive)
7|Page
MODULE 2 PHP
substr_compare() Compares two strings from a specified start position (binary safe and optionally case
Formatting Strings
8|Page
MODULE 2 PHP
• The sprintf() function is similar to the printf() function, but the only difference
between both of them is that sprint() saves the output into a string instead of
displaying the formatted message on browser like printf() function.
Syntax
The PHP date() function formats a timestamp to a more readable date and
time. Syntax
date(format,timestamp)
9|Page
Parameter Description
MODULE 2 PHP
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time
Get a Date
The required format parameter of the date() function specifies how to format the
date (or time).
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters to
add additional formatting.
<?php
echo "Today is " .
date("Y/m/d") . "<br>"; echo
"Today is " . date("Y.m.d") .
"<br>"; echo "Today is " .
date("Y-m-d") . "<br>"; echo
"Today is " . date("l"); ?>
Get a Time
Here are some characters that are commonly used for times:
10 | P a g e
MODULE 2 PHP
Example
<?php
echo "The time is ".
date("h:i:sa"); ?>
When opening a file, several different modes can be used. The most common
ones are r and w for read and write. There are several more available, though,
that will control whether to create a new file, open an existing file, and start
writing at the beginning or the end. These modes are used with open () in the
rest of the examples.
• r - read only
Write to a file
When writing files, we have two primary options that we will look at:
11 | P a g e
MODULE 2 PHP
When reading a file we have the same two primary options that we will look at:
• Reading bytes as needed with fread()
• Reading the entire file in to a variable with file_get_contents()
Common file tasks
Here are some examples of other common tasks I perform with files like:
Get filesize
It can quickly get the size of a file in bytes using the filesize() function.
<?php
echo filesize('hello.txt');
?>
<?php
echo file_exists('hello.txt');
?>
Check if file is a directory - you can use is_dir() function.
Get current working directory - you can use getcwd() function.
If we want to list the contents of a directory you have two main options:
12 | P a g e
MODULE 2 PHP
• glob() - glob() lets you search for contents in a directory using a pattern like *.* or *.png
PHP OOP
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or functions that perform operations
on the data, while object-oriented programming is about creating objects that contain both
data and functions.
<?php
13 | P a g e
MODULE 2 PHP
class Fruit {
// code goes here...
}
?>
Example
Below we declare a class named Fruit consisting of two properties ($name and
$color) and two methods set_name() and get_name() for setting and getting the
$name property:
<?php
class
Fruit
{ //
Prop
erties
publi
c
$nam
e;
publi
c
$colo
r; //
Meth
ods
function set_name($name) {
$this->name = $name;
}
function
get_name() {
return $this-
>name;
}
}
?>
14 | P a g e
MODULE 2 PHP
Note: In a class, variables are called properties and functions are called
methods.
a class once and then make many objects that belong to it. Objects are also
known as an instance.
<?php
class
MyCla
ss
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
<?
ph
cla
ss
de
mo
15 | P a g e
MODULE 2 PHP
javatpoint"; public
function display()
{
echo $this->a;
}
}
$obj = new demo();
$obj->display();
?>
What is a Constructor?
A constructor is a member function of a class that initializes the object and allocates the
memory.
A constructor has the same name as that of its class, thus it can be easily
identified.
It is always declared and defined in the public section of a class. A constructor
does not have any return type.
Therefore, it does not return anything, but it is not even void.
Syntax:
Class_name (arguments if any)
{
…
…
};
16 | P a g e
MODULE 2 PHP
A single class may have multiple constructors that are differentiated based on the number
and
type of arguments passed. There are three main types of constructors, namely, default
constructor, parameterized constructor, and copy constructor.
Example 1
<?php
Class Example
{
Public function __construct()
{
Echo “Hello”;
}
}
$obj = new Example();
$obj = new Example();
?>
What is a Destructor?
};
17 | P a g e
MODULE 2 PHP
A destructor does not have any argument and is always called in the reverse
order of the constructor. Destructor are required for destroying the objects to
release the memory allocated to them.
Example 1
<?php
class demo
{
public function demo()
{
echo “constructor1…”;
}
}
class demo1 extends demo
{
public function __construct()
{
echo parent::demo();
echo “constructor2…”;
}
public function __destruct()
{
echo “destroy…..”;
}
}
$obj= new demo1();
?>
18 | P a g e
MODULE 2 PHP
CONSTUCTOR DESTRUCTOR
Constructors are called automatically when an Destructors are called automatically when the
object is created. block is exited or when the program
terminates.
Constructors allow an object to initialize a They allow objects to execute code when it is
value before it is used. being destroyed.
They are called in the successive order of They are called in the reverse order of their
their creation. creation.
The concept of copy constructor allows an There is no such concept in the case of
object to get initialized from another object. destructors.
Abstract class:
Interface:
Inheritance:
19 | P a g e
MODULE 2 PHP
Example 1
<?php
Class a
{
function fun1()
{
echo “javatpoint”;
}
}
class b extends a
{
function fun2()
{
echo “SSSIT”;
}
}
$obj= new b();
$obj->fun1();
?>
In PHP, the keywords public, private and protected are known as the access
modifiers.
These keywords control the extent of accessibility or visibility of the class
properties and methods.
20 | P a g e
MODULE 2 PHP
One of these keywords is prefixed while declaring the member variables and
defining member functions.
Whether the PHP code has free access to a class member, or it is restricted
from getting access, or it has conditional access, is determined by these
keywords –
EXAMPLE 1: Public
<?php
class Demo
{
public $name = "Ajeet";
function disp()
{
echo $this->name . "<br/>";
}
}
class Child extends Demo
{
function show() Output
{
echo $this->name;
}
}
$obj = new Child();
echo $obj->name . "<br/>";
$obj->disp();
$obj->show();
?>
21 | P a g e
MODULE 2 PHP
EXAMPLE 2: Private
<?php
class Hello
{
private $name = "Sonoo";
private function show()
{
echo "This is a private method of the parent class.<br/>";
}
}
class Child extends Hello
{
public function show1()
{
echo "Cannot access private property of the parent class.<br/>";
}
} output
$obj = new Child();
$obj->show1();
?>
EXAMPLE 3: Protected
<?php
class Hello
{
protected $x = 500;
protected $y = 100;
function add()
{
echo $this->x + $this->y . "<br/>";
}
} output
class Child extends Hello
{
function sub()
{
echo $this->x - $this->y . "<br/>";
}
}
$obj = new Child();
$obj->add();
$obj->sub();
?>
22 | P a g e
MODULE 2 PHP
PHP – Constants
A constant in PHP is a name or an identifier for a simple value. A constant value cannot change
during the execution of the PHP script.
Note: Unlike variables, constants are automatically global throughout the script.
23 | P a g e
MODULE 2 PHP
Use the define () function to create a constant. It defines constant at run time.
Syntax:
File: constant1.php
<?php
echo MESSAGE;
?>
Traits in PHP
PHP only supports single inheritance: a child class can inherit only from one single parent.
So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.
• Traits are used to declare methods that can be used in multiple classes.
• Traits can have methods and abstract methods that can be used in multiple
classes, and the methods can have any access modifier (public, private, or
protected).
• Traits are declared with the trait keyword:
24 | P a g e
MODULE 2 PHP
Syntax:
<?php
trait traitname {
// some code…
}
?>
Syntax
<?php
class MyClass {
use TraitName;
}
?>
Static methods can be called directly – without creating an instance of the class first.
Static methods are declared with the static keyword:
The “static” keyword in PHP defines static properties and methods in a PHP class.
It may also be noted that the static keyword defines static variables and static
anonymous functions.
The syntax of a static method call is
class ClassName {
public static function methodName() {
// Code for the static method
}
}
Example
<?php
class Greeting
{
public static function welcome() output
{
echo "Hello World!";
}
}
25 | P a g e
MODULE 2 PHP
Syntax
ClassName::$staticProperty;
Example
<?php
class Pi output
{
public static $value = 3.14159;
}
// Get static property
echo Pi::$value;
?>
PHP – Namespaces
Advantages of Namespace
26 | P a g e
MODULE 2 PHP
Defining a Namespace
namespace myspace;
A “.php” file containing a namespace must declare the namespace at the top of
the file before any other (except the declare directive). Declaration of class,
function and constants inside a namespace affects its access.
An iterable is any value that can be looped through with a foreach() loop.
The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a
data type for function arguments and function return values.
PHP – Using Iterables - The iterable keyword can be used as a data type of a function argument
or as the return type of a function:
Example :
<?php
function printIterable(iterable $myIterable) { output
foreach ($myIterable as $item) {
echo $item . "<br/>";
}
}
$arr = ["a", "b", "c"];
printIterable($arr);
?>
27 | P a g e