Unit II (PHP)
Unit II (PHP)
1. PHP Functions
Definition
A PHP function is a block of code that can be defined once and called multiple
times. Functions help to make the code reusable, modular, and easier to maintain.
Rules
Types
Syntax
Program
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
?>
Output
1
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Hello, Alice!
Result
The function greet() is called with the parameter "Alice", and it returns the greeting
string.
Advantages
Disadvantages
2. Defining a Function
Definition
Rules
Syntax
function functionName() {
// Code to execute
}
Program
<?php
function sayHello() {
echo "Hello, World!";
2
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
}
sayHello(); // Calling the function
?>
Output
Hello, World!
Result
The function sayHello() is defined and called, which outputs the message.
Advantages
● Code organization.
● Functions can be reused multiple times across the code base.
Disadvantages
3. Returning a Value
Definition
A PHP function can return a value back to the calling code using the return
keyword. This allows functions to provide computed results or data.
Rules
Syntax
Program
3
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
<?php
function add($a, $b) {
return $a + $b;
}
Output
15
Result
The add() function returns the sum of 5 and 10, which is then printed.
Advantages
Disadvantages
4. Returning an Array
Definition
A PHP function can return an array, which allows you to send multiple values from
a function back to the caller.
Rules
Syntax
function getValues() {
4
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Program
<?php
function getValues() {
return [1, 2, 3];
}
$array = getValues();
print_r($array); // Outputs Array ( [0] => 1 [1] => 2 [2] => 3 )
?>
Output
Result
Advantages
Disadvantages
5. Passing by Reference
Definition
In PHP, you can pass arguments to functions by reference, meaning the function
can modify the original variable.
Rules
● Pass by reference is done using the & symbol before the argument.
5
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
● Changes made to the variable inside the function will affect the original
variable.
Syntax
function modifyValue(&$var) {
$var = $var * 2;
}
Program
<?php
function modifyValue(&$var) {
$var = $var * 2;
}
$num = 10;
modifyValue($num);
echo $num; // Outputs 20
?>
Output
20
Result
The value of $num is modified inside the function since it was passed by reference.
Advantages
Disadvantages
● Makes code harder to understand since changes are made outside the
function scope.
● Risk of unintentional modifications to original data.
6
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Definition
PHP allows access to global variables inside functions using the global keyword or
by using the $GLOBALS array.
Rules
Syntax
$var = 10;
function accessGlobal() {
global $var;
echo $var;
}
Program
<?php
$var = 5;
function accessGlobal() {
global $var;
echo $var;
}
accessGlobal(); // Outputs 5
?>
Output
Result
The global variable $var is accessed inside the function using the global keyword.
7
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Advantages
Disadvantages
● Using global variables excessively can make the code harder to maintain.
● Can lead to unwanted side effects if variables are modified unintentionally.
Definition
Rules
● Local Scope: Variables defined inside a function are only available within
that function.
● Global Scope: Variables defined outside any function are available globally
unless accessed within functions using global or $GLOBALS.
● Static Scope: Variables declared as static retain their values between
function calls.
Syntax
function myFunction() {
$localVar = 10; // Local scope
static $staticVar = 0; // Static variable
$staticVar++;
echo $staticVar;
}
Program
<?php
$globalVar = "I'm global";
8
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
function myFunction() {
global $globalVar;
$localVar = "I'm local";
static $staticVar = 0;
myFunction();
?>
Output
I'm global
I'm local
1
Result
● The global variable $globalVar is accessed inside the function using global.
● The local variable $localVar can only be accessed inside the function.
● The static variable $staticVar retains its value between function calls.
Advantages
Disadvantages
Definition
In PHP, including and requiring files allow you to insert the contents of one PHP
file into another. This helps in organizing code into reusable parts, keeping the
project structured and maintainable.
Rules
Types
1. include: Includes the file. If the file is not found, PHP issues a warning but
continues execution.
2. require: Includes the file. If the file is not found, PHP issues a fatal error
and stops execution.
3. include_once: Includes the file only once. If the file has already been
included, it will not be included again.
4. require_once: Same as require, but only includes the file once.
Syntax
include 'file.php';
require 'file.php';
include_once 'file.php';
require_once 'file.php';
Program
<?php
// Assuming "header.php" exists and contains HTML header content
include 'header.php';
echo "Welcome to the homepage!";
?>
Output
10
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Result
Advantages
● Reusability: You can reuse code (functions, classes, etc.) across multiple
files.
● Modularity: Makes it easier to maintain large codebases by breaking code
into smaller, manageable files.
● Prevents redundancy: Common code can be included across different files,
avoiding duplication.
Disadvantages
● File inclusion errors: If the file path is incorrect or the file is missing, it can
result in warnings or errors.
● Performance: Excessive use of includes/requires can slow down
performance if files are large or if too many files are included.
Definition
The include statement allows you to include and evaluate a specified PHP file
during the execution of the script. If the file cannot be found, PHP will issue a
warning, but the script will continue executing.
Rules
Syntax
include 'file.php';
Program
11
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
<?php
include 'header.php'; // Includes the header file
echo "This is the main content.";
?>
Output
Result
The contents of header.php are included, and the message "This is the main
content." is printed afterward.
Advantages
Disadvantages
Definition
The include_once statement ensures that a file is included only once, even if it is
called multiple times in the script. This helps prevent redeclaration errors (e.g.,
function or class redeclaration).
Rules
● The file will be included only once, regardless of how many times the
include_once is called.
● If the file has already been included, it will not be included again.
Syntax
include_once 'file.php';
12
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Program
<?php
include_once 'header.php'; // Includes the file once
include_once 'header.php'; // Won't include again
echo "This is the main content.";
?>
Output
Result
The file header.php is included only once, even if the include_once statement
appears multiple times.
Advantages
Disadvantages
Definition
require is similar to include, but if the file cannot be found, it results in a fatal
error, stopping the script. require_once ensures the file is included only once.
Rules
Syntax
13
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
require 'file.php';
require_once 'file.php';
Program
<?php
require 'header.php'; // File must be found, or script will stop
echo "Main content here.";
?>
Output
If header.php is missing:
Result
If the file is missing, the script will stop execution with a fatal error.
Advantages
● Ensures critical files are included: require is ideal when the file is essential
for the script to function.
● Prevents multiple inclusions: require_once ensures the file is included only
once.
Disadvantages
● Fatal errors: If the required file is missing, the script will halt execution.
● Performance overhead: Checking for repeated inclusions can affect
performance if overused.
Definition
In PHP, objects are instances of classes, and they represent real-world entities.
Objects encapsulate data (properties) and behavior (methods) related to that entity.
Terminology
14
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Definition
Rules
Syntax
class ClassName {
// Properties and methods go here
}
Program
<?php
class Car {
public $make;
public $model;
public $year;
function startEngine() {
echo "Engine started!";
}
}
?>
Output
15
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Result
The class Car is declared with three properties and one method.
Definition
An object is created using the new keyword followed by the class name.
Rules
Syntax
Program
<?php
class Car {
public $make;
public $model;
function startEngine() {
echo "Engine started!";
}
}
Output
Copy code
Toyota
16
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Result
The object $myCar is created from the Car class and its property make is accessed.
Definition
Accessing an object's properties and methods is done using the -> operator.
Rules
Syntax
$object->property;
$object->method();
Program
<?php
class Car {
public $make;
public $model;
function startEngine() {
echo "Engine started!";
}
}
Output
Copy code
Engine started!
17
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Result
16. Constructors
Definition
Rules
Syntax
Program
<?php
class Car {
public $make;
public $model;
Output
18
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Toyota
Result
The constructor initializes the make and model properties when the object is
created.
Definition
Methods are functions that belong to a class. They define the behavior of an object.
Rules
Syntax
function methodName() {
// Method body
}
Program
<?php
class Car {
public $make;
public $model;
function startEngine() {
echo "Engine started!";
}
}
Output
19
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Engine started!
Result
Definition
Properties in a class are variables that hold data related to an object. They are
declared within the class.
Rules
Syntax
public $propertyName;
private $propertyName;
Program
<?php
class Car {
public $make;
private $model;
Result
Definition
Constants are similar to variables, but their values cannot be changed after they are
defined. They are declared using the const keyword.
Rules
Syntax
Program
<?php
class Car {
const WHEELS = 4;
}
Output
Result
The constant WHEELS is accessed using Car::WHEELS and its value is displayed.
20. Inheritance
Definition
Inheritance allows one class to inherit the properties and methods of another class.
It helps in creating a hierarchy of classes and promotes code reuse.
Rules
21
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
● The subclass inherits the public and protected properties and methods of the
parent class.
● Use the extends keyword to create a subclass.
Syntax
Program
<?php
class Vehicle {
public $make;
public function move() {
echo "Moving...";
}
}
Output
Moving...
Result
The Car class inherits the move() method from the Vehicle class and calls it.
Definition
22
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
An array in PHP is a data structure that allows you to store multiple values in a
single variable. Arrays can hold values of different data types, including integers,
strings, and even other arrays.
Rules
Types
Syntax
// Associative array
$array = ["name" => "John", "age" => 30];
// Multidimensional array
$array = [
["name" => "John", "age" => 30],
["name" => "Jane", "age" => 28]
];
Definition
Basic access refers to retrieving data from an array using the array index or key.
Rules
23
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Syntax
Program
<?php
// Numerically Indexed Array
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[1]; // Outputs "Banana"
// Associative Array
$person = ["name" => "Alice", "age" => 25];
echo $person["name"]; // Outputs "Alice"
?>
Output
Banana
Alice
Result
Data from the array is accessed correctly using either the numeric index or the key
name.
Advantages
Disadvantages
24
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
● Arrays can become difficult to manage when dealing with large amounts of
data.
● Associative arrays are slower to access compared to numerically indexed
arrays.
Definition
Numerically indexed arrays are arrays where the keys are automatically assigned
numeric values starting from 0.
Rules
Syntax
Program
<?php
$numbers = [10, 20, 30, 40];
echo $numbers[2]; // Outputs "30"
?>
Output
30
Result
Access the third element in the numerically indexed array using its index 2.
Advantages
Disadvantages
25
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
● Less flexible than associative arrays when dealing with non-sequential data.
Definition
Associative arrays are arrays where each element is accessed using a key rather
than a numeric index.
Rules
Syntax
Program
<?php
$person = ["name" => "John", "age" => 30];
echo $person["age"]; // Outputs "30"
?>
Output
30
Result
Advantages
Disadvantages
26
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Definition
The array() keyword is used to create arrays in PHP, especially in earlier versions
of PHP (before PHP 5.4). Starting from PHP 5.4, square brackets [] can also be
used.
Rules
Syntax
Program
<?php
$numbers = array(10, 20, 30, 40);
echo $numbers[0]; // Outputs "10"
?>
Output
10
Result
Advantages
Disadvantages
27
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Definition
Multidimensional arrays are arrays that contain other arrays, essentially creating a
matrix or nested structure.
Rules
Syntax
$array = [
[1, 2, 3],
[4, 5, 6]
];
Program
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6]
];
echo $matrix[1][2]; // Outputs "6"
?>
Output
Result
A multidimensional array is accessed using two indices: one for the row and one
for the column.
Advantages
Disadvantages
Definition
PHP offers several built-in functions to manipulate and work with arrays. These
functions allow you to perform operations like sorting, counting, or modifying
array elements.
Types of Functions
1. is_array()
Definition
Rules
Syntax
is_array($variable);
Program
29
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
<?php
$var = [1, 2, 3];
if (is_array($var)) {
echo "It's an array!";
}
?>
Output
It's an array!
Result
Advantages
Disadvantages
2. count()
Definition
Rules
Syntax
count($array);
Program
<?php
$fruits = ["Apple", "Banana", "Orange"];
30
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Output
Result
Advantages
Disadvantages
● Does not work for non-array data types (unless checked with is_array()
first).
3. sort()
Definition
Rules
Syntax
sort($array);
Program
<?php
$numbers = [3, 1, 2];
sort($numbers);
print_r($numbers);
31
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
?>
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Result
Advantages
Disadvantages
● Sorts the original array (use asort() or ksort() for more control).
● Sorting can be slow for large datasets.
4. shuffle()
Definition
Rules
Syntax
shuffle($array);
Program
32
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
<?php
$cards = ["Ace", "King", "Queen"];
shuffle($cards);
print_r($cards);
?>
Output
Array
(
[0] => King
[1] => Queen
[2] => Ace
)
Result
Advantages
Disadvantages
5. explode()
Definition
Rules
● The delimiter is the character that separates the string into elements of the
array.
● Returns an array of strings.
Syntax
33
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
explode($delimiter, $string);
Program
<?php
$sentence = "apple,banana,orange";
$fruits = explode(",", $sentence);
print_r($fruits);
?>
Output
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Result
The string is split into an array of fruits based on the comma delimiter.
Advantages
Disadvantages
● Can only split by a single delimiter (if complex patterns are needed, use
preg_split()).
6. extract()
Definition
The extract() function imports variables from an array into the current symbol
table.
Rules
34
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Syntax
extract($array);
Program
<?php
$array = ["name" => "John", "age" => 30];
extract($array);
echo $name; // Outputs "John"
?>
Output
John
Result
The variables $name and $age are extracted from the $array and used as individual
variables.
Advantages
Disadvantages
● Can cause naming conflicts if array keys are already used as variable names.
● Should be used cautiously to avoid overwriting existing variables.
7. compact()
Definition
The compact() function creates an array from variables and their values.
Rules
35
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Syntax
compact($var1, $var2);
Program
<?php
$name = "John";
$age = 30;
$array = compact("name", "age");
print_r($array);
?>
Output
Array
(
[name] => John
[age] => 30
)
Result
An associative array is created with variable names as keys and their values as
values.
Advantages
Disadvantages
● Can lead to confusion if variable names are not clearly defined or if there are
naming conflicts.
Definition
36
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV
Rules
Syntax
reset($array);
end($array);
Program
<?php
$array = [1, 2, 3, 4];
echo reset($array); // Outputs "1"
echo end($array); // Outputs "4"
?>
Output
1
4
Result
The functions set the internal pointer to the first or last element and return the
corresponding value.
Advantages
Disadvantages
● Modifies the internal array pointer, which could affect other functions or
loops.
37