Unit-3 Array and Functions in PHP
Unit-3 Array and Functions in PHP
Technology
Unit – 3 Array and Functions in PHP
Array
• An array is a data structure that can hold
multiple values under a single name. It is a
versatile and fundamental part of the language,
used extensively for storing and manipulating
collections of data.
2
Types of Array
• Indexed arrays: These arrays use numeric keys to access elements. The
keys start from 0 and increase sequentially. Elements are stored and
accessed by their numeric index.
• $colors = array("Red", "Green", "Blue");
• echo $colors[0]; // Outputs: Red
• Associative arrays: In associative arrays, keys are user-defined rather
than being numeric. Each key is associated with a value, and you can
access elements using these keys.
• $student = array("name" => "John", "age" => 25, "grade" => "A");
• echo $student["name"]; // Outputs: John
3
Types of Array
• Multidimensional arrays: These are arrays that contain other arrays
as elements. They can be considered as arrays of arrays.
• $matrix = array(
• array(1, 2, 3),
• array(4, 5, 6),
• array(7, 8, 9)
• );
• echo $matrix[1][2]; // Outputs: 6
4
Types of Array
• Dynamic arrays: PHP allows arrays to grow or shrink dynamically,
meaning you can add or remove elements at any time without
explicitly specifying the size.
• $fruits = array();
• $fruits[] = "Apple";
• $fruits[] = "Banana";
• $fruits[] = "Orange";
5
Types of Array
• Typed arrays (PHP 7.4 and later): PHP 7.4 introduced support for typed properties and typed
arrays. You can specify the type of values that an array can hold using type declarations.
• class MyClass {
• public array $numbers;
•
• public function __construct() {
• $this->numbers = [];
• }
• }
7
Array Functions
• array_push(): Pushes one or more elements onto the end of an array.
• $stack = array("orange", "banana");
• array_push($stack, "apple", "raspberry");
• print_r($stack); // Output: Array ( [0] => orange [1] => banana [2] =>
apple [3] => raspberry )
8
Array Functions
• array_pop(): Removes the last element from an array and returns it.
• $stack = array("orange", "banana", "apple");
• $fruit = array_pop($stack);
• echo $fruit; // Output: apple
• array_shift(): Shifts the first element off an array and returns it,
shortening the array by one element.
• $queue = array("orange", "banana", "apple");
• $fruit = array_shift($queue);
• echo $fruit; // Output: orange
9
Array Functions
• array_unshift(): Prepend one or more elements to the beginning of an array.
• $queue = array("orange", "banana");
• array_unshift($queue, "apple", "raspberry");
• print_r($queue); // Output: Array ( [0] => apple [1] => raspberry [2] => orange
[3] => banana )
• array_key_exists(): Checks if the specified key exists in the array.
• $age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
• if (array_key_exists("Ben", $age)) {
• echo "Ben is " . $age['Ben'] . " years old.";
• }
10
Array Functions
in_array(): Checks if a value exists in an array.
• $fruits = array("apple", "banana", "orange");
• if (in_array("banana", $fruits)) {
• echo "Found banana!";
•}
array_search(): Searches the array for a given value and returns the first
corresponding key if successful.
$fruits = array("a" => "apple", "b" => "banana", "c" => "orange");
$key = array_search("banana", $fruits);
echo $key; // Output: b
11
Miscellaneous Functions
• define: define() is a function used to define constants in PHP.
Constants are identifiers (names) for simple values that cannot
change during the execution of the script.
define("PI", 3.14);
echo PI; // Outputs: 3.14
• Include: include is a statement used to include and evaluate the
specified file in the current PHP script. If the file cannot be included, it
generates a warning but does not stop the execution of the script
• include 'header.php';
12
Miscellaneous Functions
• Require: require is similar to include but generates a fatal error if the
specified file cannot be included, halting the script's execution.
• require 'header.php';
• Header: header() is a function used to send HTTP headers to the
client browser. It must be called before any actual output is sent.
Headers are used to provide additional information to the browser,
such as redirecting to another page, setting cookies, or specifying
content types.
• header('Location: http://example.com');
13
Miscellaneous Functions
• Die: die() is a language construct in PHP used to terminate the script immediately and print a message.
It's commonly used for error handling or to stop script execution under certain conditions.
• $x = 10;
• if ($x > 5) {
• die("Error: Value cannot be greater than 5");
• }
• Exit: exit() is similar to die() and is used to terminate the script immediately. It can also be used to
return a value to the calling code if desired.
• $x = 10;
• if ($x > 5) {
• exit("Error: Value cannot be greater than 5");
• }
14
Overview of built in functions of
PHP
• you can work with date and time using various functions provided by
the language's built-in DateTime class and related functions. Here's a
brief overview of some commonly used date and time functions in
PHP:
• Current Date and Time:
• date() - Returns the current date and time formatted according to the
specified format.
• echo date("Y-m-d H:i:s"); // Output: 2024-02-20 15:30:00
15
Overview of built in functions of
PHP
• Creating a DateTime Object:
• new DateTime() - Creates a new DateTime object representing the current date and
time.
• $now = new DateTime();
• echo $now->format("Y-m-d H:i:s"); // Output: 2024-02-20 15:30:00
• Formatting Dates:
• DateTime::format() - Formats the DateTime object according to the specified
format.
• $date = new DateTime('2024-02-20');
• echo $date->format('Y-m-d'); // Output: 2024-02-20
16
Overview of built in functions of
PHP
• Date Arithmetic:
• DateTime::modify() - Modifies the DateTime object.
• $date = new DateTime('2024-02-20');
• $date->modify('+1 day');
• echo $date->format('Y-m-d'); // Output: 2024-02-21
• Timezone Handling:
• date_default_timezone_set() - Sets the default timezone used by all
date/time functions.
• date_default_timezone_set('America/New_York');
17
Overview of built in functions of
PHP
• Date Comparison:
• DateTime::diff() - Returns the difference between two DateTime
objects.
• $date1 = new DateTime('2024-02-20');
• $date2 = new DateTime('2024-02-25');
• $diff = $date1->diff($date2);
• echo $diff->format('%R%a days'); // Output: +5 days
18
Math Functions
Basic Arithmetic Functions:
•abs($number): Returns the absolute value of a number.
•sqrt($number): Returns the square root of a number.
•pow($base, $exponent): Returns base raised to the power of exponent.
•exp($number): Returns the exponential value of a number.
•log($number, $base): Returns the natural logarithm (base e) or
logarithm to the specified base.
•log10($number): Returns the base-10 logarithm of a number.
•round($number, $precision): Rounds a floating-point number to a
specified precision.
19
Math Functions
Trigonometric Functions:
•sin($angle), cos($angle), tan($angle): Returns the
sine, cosine, and tangent of an angle (in radians).
•asin($number), acos($number), atan($number):
Returns the arcsine, arccosine, and arctangent of a
number, respectively.
20
Math Functions
Random Number Generation:
•rand($min, $max): Generates a random integer
between the specified minimum and maximum values.
•mt_rand($min, $max): Generates a random integer
using the Mersenne Twister algorithm.
•random_int($min, $max): Generates a
cryptographically secure random integer.
•mt_srand($seed): Seeds the random number
generator for mt_rand().
21
Math Functions
• Math Constants:
•M_PI: Value of π (pi).
•M_E: Value of e (Euler's number).
22
Math Functions
• Example:
• $number = -4.5;
26
File Handling Functions
Directory Handling:
• opendir(): Opens a directory handle.
• readdir(): Reads from a directory handle.
• closedir(): Closes a directory handle.
File Locking:
• flock(): Locks or releases a file.
• Error Handling:
• feof(): Tests for end-of-file on a file pointer.
• ferror(): Returns the last error on the file pointer.
27
File Handling Functions
<?php
// File paths
$filename = 'example.txt';
$sourceFile = 'source.txt';
$destinationFile = 'destination.txt';
28
File Handling Functions
// Reading file contents
$fileContents = fread($file, filesize($filename));
30
File Handling Functions
// Copying a file
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully.";
} else {
echo "Failed to copy file.";
}
31
File Handling Functions
// Deleting a file
if (unlink($sourceFile)) {
echo "File deleted successfully.";
} else {
echo "Failed to delete file.";
}
?>
32
String Functions
PHP offers a wide range of string functions to manipulate and work
with strings effectively. Here are some commonly used string functions
in PHP:
strlen($string): Returns the length of the string.
$string = "Hello, world!";
echo strlen($string); // Output: 13
strtolower($string): Converts string to lowercase.
$string = "Hello, WORLD!";
echo strtolower($string); // Output: hello, world!
33
String Functions
strtoupper($string): Converts string to uppercase.
• $string = "Hello, world!";
• echo strtoupper($string); // Output: HELLO, WORLD!
substr($string, $start, $length): Returns a part of the string starting
from $start with a length of $length
• $string = "Hello, world!";
• echo substr($string, 0, 5); // Output: Hello
34
String Functions
str_replace($search, $replace, $string): Replaces all occurrences of
$search in $string with $replace.
• $string = "Hello, world!";
• echo str_replace("world", "PHP", $string); // Output: Hello, PHP!
strpos($string, $substring): Returns the position of the first occurrence
of $substring in $string.
• $string = "Hello, world!";
• echo strpos($string, "world"); // Output: 7
35
String Functions
trim($string): Removes whitespace or other predefined characters from
both the beginning and the end of a string.
• $string = " Hello, world! ";
• echo trim($string); // Output: Hello, world!
explode($delimiter, $string): Splits a string into an array by a specified
delimiter.
• $string = "apple,banana,orange";
• $array = explode(",", $string);
• print_r($array); // Output: Array ( [0] => apple [1] => banana [2] =>
orange )
36
String Functions
implode($glue, $array): Joins array elements with a string.
• $array = array("apple", "banana", "orange");
• $string = implode(", ", $array);
• echo $string; // Output: apple, banana, orange
37
User Defined Functions
• user-defined functions allow you to encapsulate a block of code that
can be reused throughout your application. Here's how you can
define and use user-defined functions in PHP:
38
User Defined Functions
<?php
// Define a basic function
function greet() {
echo "Hello, World!";
}
// Call the function
greet(); // Output: Hello, World!
// Define a function with parameters
function greetUser($name) {
echo "Hello, $name!";
}
39
User Defined Functions
// Call the function with an argument
greetUser("John"); // Output: Hello, John!
// Define a function with a return value
function add($a, $b) {
return $a + $b;
}
41