0% found this document useful (0 votes)
5 views37 pages

Unit II (PHP)

The document provides an overview of PHP functions, including their definitions, types, syntax, advantages, and disadvantages. It covers various aspects such as defining functions, returning values, passing by reference, accessing global variables, and including files. Additionally, it introduces PHP objects and classes, explaining how to declare a class and create an object.

Uploaded by

varnikhasree057
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views37 pages

Unit II (PHP)

The document provides an overview of PHP functions, including their definitions, types, syntax, advantages, and disadvantages. It covers various aspects such as defining functions, returning values, passing by reference, accessing global variables, and including files. Additionally, it introduces PHP objects and classes, explaining how to declare a class and create an object.

Uploaded by

varnikhasree057
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

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

● Functions in PHP are defined using the function keyword.


● A function can take parameters (optional) and return a value (optional).
● Function names are case-insensitive, but it’s recommended to use lowercase.
● Functions can be called any number of times.
● The body of a function is enclosed in curly braces {}.

Types

1. User-defined functions: Functions that you define in your script.


2. Built-in functions: Predefined functions in PHP (e.g., echo(), strlen()).
3. Anonymous functions: Functions without a name, often used in callback
scenarios.

Syntax

function functionName($param1, $param2) {


// Code to be executed
return $result;
}

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

● Reusability: Functions can be reused throughout the script.


● Modularity: Breaks down complex problems into smaller, manageable parts.
● Code readability: Functions improve the readability and structure of code.

Disadvantages

● Over use can lead to unnecessary complexity.


● Can become harder to debug if not organized properly.

2. Defining a Function

Definition

Defining a function means creating a function by specifying its name, parameters


(if any), and the block of code to execute.

Rules

● A function must be defined before it is called, unless it’s defined in an


included file.
● Function names should follow valid naming conventions.

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

● If overused, it may become difficult to maintain the code.

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

● A function can only return one value at a time.


● The return statement ends the function execution immediately.
● The returned value can be assigned to a variable.

Syntax

function add($a, $b) {


return $a + $b;
}

Program

3
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

<?php
function add($a, $b) {
return $a + $b;
}

$result = add(5, 10);


echo $result; // Outputs 15
?>

Output

15

Result

The add() function returns the sum of 5 and 10, which is then printed.

Advantages

● Allows functions to provide results to other parts of the program.


● Helps to encapsulate functionality and hide implementation details.

Disadvantages

● Only a single value can be returned unless using arrays or objects.


● Function must return before executing any further code.

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

● Arrays can be returned like any other value.


● Arrays can be multidimensional.

Syntax

function getValues() {
4
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

return [1, 2, 3];


}

Program

<?php
function getValues() {
return [1, 2, 3];
}

$array = getValues();
print_r($array); // Outputs Array ( [0] => 1 [1] => 2 [2] => 3 )
?>

Output

Array ( [0] => 1 [1] => 2 [2] => 3 )

Result

The function getValues() returns an array, which is printed using print_r().

Advantages

● Can return multiple values at once.


● Allows complex data to be returned in a structured way.

Disadvantages

● The caller must be prepared to handle the returned array.


● Can be inefficient with large arrays or very complex data structures.

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

● Allows functions to modify the original value of a variable.


● Useful for large data sets to avoid copying data.

Disadvantages

● Makes code harder to understand since changes are made outside the
function scope.
● Risk of unintentional modifications to original data.

6. Returning Global Variables

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

● Global variables must be declared within a function using global or accessed


via $GLOBALS.
● Global variables can be modified from within the function.

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

● Makes global variables available inside functions.


● Useful when dealing with values that are used across different parts of the
script.

Disadvantages

● Using global variables excessively can make the code harder to maintain.
● Can lead to unwanted side effects if variables are modified unintentionally.

7. Recap of Variable Scope

Definition

Variable scope refers to the context in which a variable can be accessed or


modified. There are different scopes in PHP: global, local, and static.

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;

echo $globalVar; // Accessing global variable


echo $localVar; // Accessing local variable
$staticVar++;
echo $staticVar; // Static variable retains its value
}

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

● Local variables prevent interference with other parts of the code.


● Static variables can be useful for counting or preserving state between
function calls.

Disadvantages

● Global variables can lead to unintended side effects if not carefully


managed.
● Static variables can make debugging harder if they hold state that changes
unexpectedly.

8. Including and Requiring Files


9
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

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

● Files can be included multiple times, depending on the statement used


(include, require).
● File inclusion happens at runtime.
● Paths to the files can be relative or absolute.
● Include files must exist at the time the script runs.

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

Header content from header.php


Welcome to the homepage!

Result

The content of header.php is included, and the message "Welcome to the


homepage!" is printed.

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.

9. The include Statement

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

● If the specified file is not found, a warning will be issued.


● The file is included and evaluated where the include statement appears.

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

Header content from header.php


This is the main content.

Result

The contents of header.php are included, and the message "This is the main
content." is printed afterward.

Advantages

● Simple to use for including reusable code.


● Continues executing the script even if the included file is not found.

Disadvantages

● If the file is missing, a warning is issued, but the script continues.


● Potentially inefficient if the same file is included multiple times.

10. Using include_once

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

Header content from header.php


This is the main content.

Result

The file header.php is included only once, even if the include_once statement
appears multiple times.

Advantages

● Prevents errors from including the same file multiple times.


● Useful for including files that declare classes or functions.

Disadvantages

● Performance impact if misused in large scripts, especially when the check


for inclusion is done multiple times.

11. Using require and require_once

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

● require: Stops the script if the file is missing.


● require_once: Ensures a file is included only once, like include_once.

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:

Fatal error: require(): Failed opening required 'header.php'

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.

12. PHP Objects

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

● Class: Blueprint for creating objects.


● Object: Instance of a class.
● Method: Function defined inside a class.
● Property: Variable defined inside a class.

13. Declaring a Class

Definition

A class in PHP is a template for creating objects. It can contain properties


(variables) and methods (functions).

Rules

● The class keyword is used to declare a class.


● Class names should follow proper naming conventions, typically starting
with an uppercase letter.

Syntax

class ClassName {
// Properties and methods go here
}

Program

<?php
class Car {
public $make;
public $model;
public $year;

function startEngine() {
echo "Engine started!";
}
}
?>

Output

No output here since no object is created yet.

15
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

Result

The class Car is declared with three properties and one method.

14. Creating an Object

Definition

An object is created using the new keyword followed by the class name.

Rules

● Use the new keyword to instantiate an object.


● An object represents an instance of a class.

Syntax

$object = new ClassName();

Program

<?php
class Car {
public $make;
public $model;

function startEngine() {
echo "Engine started!";
}
}

$myCar = new Car(); // Creating an object


$myCar->make = "Toyota";
$myCar->model = "Corolla";
echo $myCar->make; // Outputs "Toyota"
?>

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.

15. Accessing Objects

Definition

Accessing an object's properties and methods is done using the -> operator.

Rules

● The -> operator is used to access properties and methods of an object.

Syntax

$object->property;
$object->method();

Program

<?php
class Car {
public $make;
public $model;

function startEngine() {
echo "Engine started!";
}
}

$myCar = new Car();


$myCar->make = "Honda";
$myCar->startEngine(); // Accessing method
?>

Output

Copy code
Engine started!

17
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

Result

The method startEngine() is called on the object $myCar.

16. Constructors

Definition

A constructor is a special method in a class that is automatically called when an


object is instantiated. It is used to initialize object properties.

Rules

● Constructors are defined with the __construct() method.


● It is called automatically when a new object is created.

Syntax

function __construct($param1, $param2) {


// Initialization code
}

Program

<?php
class Car {
public $make;
public $model;

function __construct($make, $model) {


$this->make = $make;
$this->model = $model;
}
}

$myCar = new Car("Toyota", "Corolla"); // Constructor automatically called


echo $myCar->make; // Outputs "Toyota"
?>

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.

17. Writing Methods

Definition

Methods are functions that belong to a class. They define the behavior of an object.

Rules

● Methods are defined within the class.


● Methods can be public, private, or protected, controlling their accessibility.

Syntax

function methodName() {
// Method body
}

Program

<?php
class Car {
public $make;
public $model;

function startEngine() {
echo "Engine started!";
}
}

$myCar = new Car();


$myCar->startEngine(); // Calls the method
?>

Output

19
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

Engine started!

Result

The startEngine() method is called on the object $myCar.

18. Declaring Properties

Definition

Properties in a class are variables that hold data related to an object. They are
declared within the class.

Rules

● Properties can be public, private, or protected.


● Public properties can be accessed directly.

Syntax

public $propertyName;
private $propertyName;

Program

<?php
class Car {
public $make;
private $model;

function __construct($make, $model) {


$this->make = $make;
$this->model = $model;
}
}
?>

Result

Properties $make and $model are declared in the Car class.

19. Declaring Constants


20
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

Definition

Constants are similar to variables, but their values cannot be changed after they are
defined. They are declared using the const keyword.

Rules

● Constants are automatically global.


● They are typically defined using the const keyword within a class.

Syntax

const CONSTANT_NAME = value;

Program

<?php
class Car {
const WHEELS = 4;
}

echo Car::WHEELS; // Outputs "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

class ChildClass extends ParentClass {


// Additional methods and properties
}

Program

<?php
class Vehicle {
public $make;
public function move() {
echo "Moving...";
}
}

class Car extends Vehicle {


public $model;
}

$myCar = new Car();


$myCar->move(); // Inherited method
?>

Output

Moving...

Result

The Car class inherits the move() method from the Vehicle class and calls it.

21. PHP Arrays

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

● Arrays can be indexed numerically or associatively.


● Arrays are zero-indexed by default.
● PHP arrays are dynamic, meaning they can grow or shrink in size.

Types

1. Numerically Indexed Arrays: Arrays where each element is accessed by a


number (index).
2. Associative Arrays: Arrays where each element is accessed by a named key
(index).
3. Multidimensional Arrays: Arrays that contain other arrays, forming a
matrix-like structure.

Syntax

// Numerically indexed array


$array = [1, 2, 3];

// Associative array
$array = ["name" => "John", "age" => 30];

// Multidimensional array
$array = [
["name" => "John", "age" => 30],
["name" => "Jane", "age" => 28]
];

22. Basic Access

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

● Use the index or key in square brackets [] to access an element.


● In numerically indexed arrays, indices start from 0.

Syntax

// Accessing a numerically indexed array


echo $array[0];

// Accessing an associative array


echo $array["name"];

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

● Easy to use for basic data storage.


● Provides quick access to values via index/key.

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.

23. Numerically Indexed Arrays

Definition

Numerically indexed arrays are arrays where the keys are automatically assigned
numeric values starting from 0.

Rules

● PHP assigns indices starting from 0.


● You can access elements using the index.

Syntax

$array = [10, 20, 30];

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

● Simple and straightforward to use for sequential data.


● Fast access time.

Disadvantages
25
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

● Less flexible than associative arrays when dealing with non-sequential data.

24. Associative Arrays

Definition

Associative arrays are arrays where each element is accessed using a key rather
than a numeric index.

Rules

● Keys are usually strings, but can also be integers.


● PHP allows you to assign custom keys to array elements.

Syntax

$array = ["key1" => "value1", "key2" => "value2"];

Program

<?php
$person = ["name" => "John", "age" => 30];
echo $person["age"]; // Outputs "30"
?>

Output

30

Result

Access elements in an associative array using the string keys.

Advantages

● Keys can be meaningful, improving readability.


● More flexible than numerically indexed arrays for complex data.

Disadvantages

● Slower access times than numerically indexed arrays.


● Larger memory usage due to storing key-value pairs.

26
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

25. Assignment Using the array() Keyword

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

● You can define arrays using array() in any version of PHP.


● array() is still commonly used for compatibility purposes.

Syntax

$array = array(1, 2, 3, 4);

Program

<?php
$numbers = array(10, 20, 30, 40);
echo $numbers[0]; // Outputs "10"
?>

Output

10

Result

An array is created using array() and accessed by index.

Advantages

● Compatible with all PHP versions.


● Clear and explicit array creation.

Disadvantages

● Requires more typing than [] for array creation (which is a shorthand in


newer PHP versions).

27
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

26. Multidimensional Arrays

Definition

Multidimensional arrays are arrays that contain other arrays, essentially creating a
matrix or nested structure.

Rules

● Multidimensional arrays can have as many levels as needed.


● Accessing elements requires multiple indices.

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

● Useful for representing complex data structures like tables, grids, or


matrices.
28
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

● Flexible and scalable.

Disadvantages

● Accessing deeply nested arrays can be cumbersome.


● Can become complex to manage with larger datasets.

27. Using Array Functions

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(): Checks if a variable is an array.


2. count(): Counts the number of elements in an array.
3. sort(): Sorts an array in ascending order.
4. shuffle(): Randomly shuffles an array.
5. explode(): Splits a string into an array.
6. extract(): Imports variables into the current symbol table from an array.
7. compact(): Creates an array from variables and their values.
8. reset(): Sets the internal pointer to the first element.
9. end(): Sets the internal pointer to the last element.

1. is_array()

Definition

The is_array() function checks if a variable is an array.

Rules

● Returns true if the variable is an array, otherwise false.

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

The function returns true as $var is an array.

Advantages

● Useful for type-checking before performing array operations.


● Helps avoid errors when working with mixed data types.

Disadvantages

● Minor performance overhead for large datasets.

2. count()

Definition

The count() function counts the number of elements in an array.

Rules

● Returns the number of elements in an array or 0 if the array is empty.

Syntax

count($array);

Program

<?php
$fruits = ["Apple", "Banana", "Orange"];

30
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

echo count($fruits); // Outputs "3"


?>

Output

Result

The function returns the number of elements in the $fruits array.

Advantages

● Simple and fast way to get the array size.


● Helps in loops or conditional checks.

Disadvantages

● Does not work for non-array data types (unless checked with is_array()
first).

3. sort()

Definition

The sort() function sorts an array in ascending order.

Rules

● Modifies the original array.


● The array will be sorted by the values.

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

The array $numbers is sorted in ascending order.

Advantages

● Quick and efficient for sorting small to medium-sized arrays.


● Very easy to use.

Disadvantages

● Sorts the original array (use asort() or ksort() for more control).
● Sorting can be slow for large datasets.

4. shuffle()

Definition

The shuffle() function randomly shuffles the order of elements in an array.

Rules

● The original array is modified.


● This function does not return any value.

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

The order of elements in the $cards array is randomly shuffled.

Advantages

● Useful for randomizing data (e.g., card games, lottery numbers).


● Simple to use.

Disadvantages

● Alters the original array (make a copy if needed).


● No easy way to reverse the shuffle process.

5. explode()

Definition

The explode() function splits a string into an array based on a delimiter.

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

● Useful for breaking down strings into manageable parts.


● Simple and effective for parsing CSV data.

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

● Converts array keys into variable names.


● Can be used to access array elements as regular variables.

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

● Quick access to array values as separate variables.


● Makes code cleaner when dealing with associative arrays.

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

● Takes one or more variable names and returns an associative array.


● Variable names must be passed as strings.

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

● Converts variables to an array in a single step.


● Useful for passing multiple variables to functions.

Disadvantages

● Can lead to confusion if variable names are not clearly defined or if there are
naming conflicts.

8. reset() and end()

Definition
36
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-II) SEMESTER: IV

● reset(): Sets the internal array pointer to the first element.


● end(): Sets the internal array pointer to the last element.

Rules

● reset(): Returns the first element of the array.


● end(): Returns the last element of the array.

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

● Useful for traversing arrays when working with pointers.


● Helps with iterating over arrays from either end.

Disadvantages

● Modifies the internal array pointer, which could affect other functions or
loops.

37

You might also like