PHP NEW UNIT - 2
PHP NEW UNIT - 2
CHAUDHARY
Array in php
In PHP, an array is a data structure that can hold multiple values under
a single name. It can be used to store a list of items, where each item is
associated with a key.
PHP array is an ordered map (contains value on the basis of key). It is
used to hold multiple values of similar type in a single variable.
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
de ining 10 different variables, it’s easy to de ine an array of 10
length.PHP supports three types of arrays:
1. Indexed Arrays
Arrays with numeric keys.
An array which is a collection of values only is called an indexed
array
PHP index is represented by number which starts from 0. We can
store number, string and object in the PHP array. All PHP array
elements are assigned to an index number by default
Example
$fruits = ["Apple", "Banana", "Cherry"];
// or
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Outputs: Apple
2. Associative Arrays
Arrays with named keys.
If the array is a collection of key-value pairs, it is called as an
associative array. The key component of the pair can be a
number or a string, whereas the value part can be of any type.
Associative arrays store the element values in association with
key values rather than in a strict linear index order.
Example:
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"];
// or
$person = array(
"name" => "John",
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] =>
Date )
3. array_pop()
$fruits = ["Apple", "Banana", "Cherry"];
$last = array_pop($fruits);
echo $last; // Outputs: Cherry
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Banana )
4. in_array()
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array.";
} else {
echo "Banana is not in the array.";
}
// Output: Banana is in the array.
5. array_keys()
Returns all the keys of an array.
$person = ["name" => "John", "age" => 30, "city" => "New
York"];
$keys = array_keys($person);
print_r($keys);
// Output: Array ( [0] => name [1] => age [2] => city )
6. array_values()
Returns all the values of an array.
$person = ["name" => "John", "age" => 30, "city" => "New York"];
$values = array_values($person);
print_r($values);
// Output: Array ( [0] => John [1] => 30 [2] => New York )
7. array_filter()
Filters elements of an array using a callback
function.
$numbers = [1, 2, 3, 4, 5];
$filtered = array_filter($numbers, fn($num) => $num > 3);
print_r($filtered);
// Output: Array ( [3] => 4 [4] => 5 )
8. array_slice()
Extracts a portion of an array.
$fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
$slice = array_slice($fruits, 1, 3);
print_r($slice);
// Output: Array ( [0] => Banana [1] => Cherry [2] => Date )
9. array_splice()
Removes and replaces a portion of an array.
$fruits = ["Apple", "Banana", "Cherry", "Date"];
array_splice($fruits, 1, 2, ["Mango", "Pineapple"]);
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Mango [2] =>
Pineapple [3] => Date )
10. array_reverse()
Reverses the order of elements in an array.
$fruits = ["Apple", "Banana", "Cherry"];
$reversed = array_reverse($fruits);
print_r($reversed);
// Output: Array ( [0] => Cherry [1] => Banana [2] =>
Apple )
11. array_unique()
Removes duplicate values from an array.
$numbers = [1, 2, 2, 3, 4, 4, 5];
$unique = array_unique($numbers);
print_r($unique);
Output: Array([0] => 1 [1] => 2 [3] => 3 [4] => 4 [6] => 5 )
12. sort()
Sorts an array in ascending order.
$numbers = [4, 2, 8, 1];
sort($numbers);
print_r($numbers);
// Output: Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 8 )
13. array_combine()
Creates an associative array by combining two
arrays: one for keys and the other for values
$keys = ["name", "age", "city"];
$values = ["John", 30, "New York"];
$combined = array_combine($keys, $values);
print_r($combined);
// Output: Array ( [name] => John [age] => 30 [city] =>
New York )
14. array_map()
Applies a callback function to each element of an
array
$numbers = [1, 2, 3, 4];
PHP Functions
1. User-defined functions
In PHP, user-de ined functions allow you to create your own
functions to perform speci ic tasks. A user-de ined function is
created using the function keyword, followed by a name,
parameters (optional), and the function body.
Meaningful Names: Use descriptive and
meaningful function names that re lect the purpose
of the function.
Small and Focused Functions: Functions should
perform a single task and be as small as possible.
Use Parameters: Avoid using global variables
inside functions; use parameters instead to pass
data.
Avoid Side Effects: Functions should avoid
modifying global variables unless absolutely
necessary.
Syntax of User-Defined Functions
function functionName($parameter1, $parameter2) {
// Code to execute
return $result; // Optional return
}
Key points
Function name: The name must be a valid identifier and
should follow PHP naming conventions.
Parameters: Functions can accept parameters
(arguments) to work with.
Return value: Functions may return a value using the
return keyword. If no return value is provided, the
function will return NULL by default.
1. Simple Function without Parameters
// Function without parameters
function greet() {
echo "Hello, World!";
}
header.php:
<?php
echo "<h1>Welcome to My Website</h1>";
?>
You can include this file in another script as follows
main.php
<?php
include 'header.php';
echo "<p>This is the main content of the page.</p>";
?>
Output
Welcome to My Website
This is the main content of the page.
Difference between include() and require()
require will produce a fatal error (E_COMPILE_ERROR) and stop the
script
include will only produce a warning (E_WARNING) and the script will
continue
3. include_once()
The include_once statement in PHP is similar to
include, but it ensures that the specified file is
included only once during the script execution. This
prevents errors caused by multiple inclusions of the
same file, such as re-declaring classes, functions, or
variables
Syntax
include_once ('file name');
Example
file1.php
<?php
echo "This is file1.php.<br>";
?>
main.php
<?php
include_once 'file1.php';
include_once 'file1.php'; // This will not include file1.php again
// This will also not cause an error.
echo "This is the main script.";
?>
Output
This is file1.php.
This is the main script.
Key Points
1. Avoids Multiple Inclusions
Ensures that the file is included only once, even if
include_once is called multiple times
2. Error Handling
If the file is not found, include_once generates a
warning but allows script execution to continue
Include_once() Require_once()
Generates a warning if the Generates a fatal error if the
file cannot be included but file cannot be included and
continues script execution stops script execution
The script continues to The script halts immediately if
execute even if the file is the file is missing or cannot be
missing or cannot be included included
Use when the file is not Use when the file is essential
critical to the application, and for the application to function
the script can proceed correctly
without it
3. Header()
The header() function in PHP is used to send raw
HTTP headers to the browser before any output is
sent. It allows you to manipulate HTTP headers,
such as redirection, content type, cache control, and
more.
Common Uses of header()
1. Redirecting to Another Page
<?php
header("Location: https://www.example.com");
exit(); // Ensure no further code is executed
?>
The Location header tells the browser to navigate to a
different URL.
Always use exit() after redirection to stop further script
execution
2. Setting Content Type
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Hello, world!"]);
?>
Changes the Content-Type of the response. Common values:
text/html: Default for HTML content.
application/json: For JSON responses.
text/plain: For plain text responses
3. Forcing File Download
<?php
$file = 'example.pdf';
header("Content-Disposition:attachment;
filename=\"$file\"");
header("Content-Type: application/pdf");
readfile($file);
exit();
?>
The Content-Disposition header forces the browser to
download the file instead of displaying it
4. Custom HTTP Response Codes
<?php
header("HTTP/1.1 404 Not Found");
echo "Page not found";
exit();
?>
Sends a custom HTTP status code like 404 Not Found or 500
Internal Server Error
Key Notes
The header() function must be called before any
output (e.g., echo, print) is sent to the browser.
Otherwise, you get a "Headers already sent" error
You can send multiple headers by calling header()
multiple times
5. Die()
The die() function in PHP is used to terminate the
execution of a script immediately. Optionally, it can
output a message before stopping the execution. It is an
alias of the exit() function, and both work identically
1. Stopping Script Execution
When something critical fails, you can use die() to stop
the script immediately
<?php
if (!file_exists("data.txt")) {
die("Error: File not found!");
}
echo "This line will not be executed if the file is missing.";
?>
2. Database Connection Failure
<?php
$conn = mysqli_connect("localhost", "username", "password",
"database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully.";
?>
3. Debugging
You can use die() to output variable data and stop the
script for debugging purposes
<?php
$data = ["name" => "Alice", "age" => 30];
die(print_r($data, true)); // Output the array and stop execution
?>
Key Notes
die() and exit() are interchangeable. Use whichever is more
readable in context
After calling die(), no code in the script will be executed
die() is often used for basic error handling, such as halting a
script if a file is missing or a database connection fails
?>
4. getdate()
Returns an associative array containing date information
for a given timestamp
<?php
$date_info = getdate();
print_r($date_info);
?>
5. date_default_timezone_set()
Sets the default timezone for all date/time functions
<?php
// Set the timezone to New York
date_default_timezone_set('America/New_York');
// Get the current date and time in New York
echo date("Y-m-d H:i:s");
?>
6. checkdate()
Checks if a given date is valid
<?php
$month = 2;
$day = 29;
$year = 2024; // Leap year
if (checkdate($month, $day, $year)) {
echo "Valid date.";
} else {
echo "Invalid date.";
}
?>
Output
Valid date.
7. idate()
Returns a speci ic part of a date as an integer (e.g., year,
month, day)
<?php
$timestamp = time();
echo idate("Y", $timestamp); // Outputs: 2024
echo idate("m", $timestamp); // Outputs: 12
echo idate("d", $timestamp); // Outputs: 18
?>
8. date_create()
Creates a new DateTime object
<?php
$date = date_create("2024-12-18");
echo date_format($date, "Y-m-d H:i:s"); // Outputs:
2024-12-18 00:00:00
?>
9. date_add()
Adds a time interval to a DateTime object
<?php
$date = date_create("2024-12-18");
date_add($date,
date_interval_create_from_date_string("10 days"));
echo date_format($date, "Y-m-d"); // Outputs: 2024-
12-28
?>
10. date_diff()
Calculates the difference between two DateTime objects
<?php
$date1 = date_create("2024-12-18");
$date2 = date_create("2024-12-25");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days"); // Outputs: +7 days
?>
PHP Math Functions
PHP provides a variety of math functions that allow you
to perform mathematical operations such as rounding,
inding the maximum or minimum values, working
with random numbers, and performing more complex
calculations. Below are some of the commonly used
PHP math functions with examples
1. abs()
Returns the absolute value of a number
<?php
echo abs(-5); // Outputs: 5
echo abs(5); // Outputs: 5
?>
2. round()
Rounds a loating-point number to the nearest integer or
to a speci ic number of decimal places
<?php
echo round(3.456); // Outputs: 3
echo round(3.456, 2); // Outputs: 3.46
2. $_SERVER
Contains information about headers, paths, and script
locations
<?php
echo $_SERVER['PHP_SELF']; // Current script
name
echo $_SERVER['SERVER_NAME']; // Server
name
echo $_SERVER['HTTP_HOST']; // Host name
?>
3. $_REQUEST
Used to collect data from HTML forms, combining data
from $_GET, $_POST, and $_COOKIE
<?php
// Accessing form data (GET or POST)
echo $_REQUEST['username'];
?>
4. $_GET
Contains data sent via the URL query string
<?php
// URL: example.com?name=John
echo $_GET['name']; // Outputs: John
?>
5. $_POST
Contains data sent via HTTP POST
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
echo $_POST['email'];
}
?>
6. $_FILES
Used to handle ile uploads
<?php
if ($_FILES['file']['error'] == 0) {
echo "File uploaded: " . $_FILES['file']['name'];
}
?>
7. $_COOKIE
Contains data stored in cookies
<?php
// Setting a cookie
setcookie("user", "John", time() + 3600);
// Accessing a cookie
echo $_COOKIE['user']; // Outputs: John
?>
8. $_SESSION
Contains session variables
<?php
session_start();
$_SESSION['username'] = "John";
echo $_SESSION['username']; // Outputs: John
?>
9. $_ENV
Contains environment variables
<?php
echo $_ENV['HOME']; // Displays the value of the
'HOME' environment variable (if set)
?>
Working with Forms in PHP
PHP Form handling
PHP form handling refers to the process of capturing
and processing data submitted through an HTML form.
PHP can handle form data sent via the GET or POST
methods
Create an HTML Form: Use HTML to design the
form that collects user input.
Set the Form's Action and Method:
Action: Specifies the PHP script where the form
data will be sent.
Method: Defines how the data is sent (GET or POST).
Access Form Data in PHP: Use PHP's superglobal
arrays:
$_GET: For forms submitted using the GET
method.
$_POST: For forms submitted using the POST
method.
<!DOCTYPE html>
<html>
<body>
<h2>Simple Form</h2>
GET POST
Appends data to the Sends data in the
URL (visible) request body (not
visible)
Limited to 2048 No character limit.
characters (browser-
dependent)
Less secure; data More secure; data
visible in the URL hidden from URL
<body>
<form action="process.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Script (process.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Access form data
$username = $_POST["username"];
$password = $_POST["password"];
// Display data
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "Password: " . htmlspecialchars($password) . "<br>";
}
?>
Use of Hidden fields to save State
Hidden fields in an HTML form are used to pass information
from one page to another without displaying it to the user. These fields
are particularly useful in maintaining the state of an application
during navigation or when handling multiple forms across pages
How Hidden Fields Work
A hidden field is created using the <input type="hidden"> tag in
an HTML form.
Data stored in the hidden field is submitted to the server along
with the form.
The server can access the value of the hidden field through PHP
superglobals ($_POST or $_GET)
Common Use Cases
1. Maintaining State Between Pages
Hidden fields can store data, such as user input or session
identifiers, that needs to persist across multiple pages
Carrying Context Information
}
}
// Validate Email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = sanitizeInput($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// Validate Age
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = sanitizeInput($_POST["age"]);
if (!filter_var($age, FILTER_VALIDATE_INT)) {
$ageErr = "Age must be a number";
}
}
// If no errors, process data
if (empty($nameErr) && empty($emailErr) && empty($ageErr)) {
echo "Name: $name<br>Email: $email<br>Age: $age";
}
}
// Function to sanitize input
function sanitizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Explanation
Validate Each Field:
Use empty() to check if the field is filled.
Use regular expressions (e.g., preg_match()) or built-in PHP functions
(e.g., filter_var()) for specific formats.
Sanitize Input:
Use htmlspecialchars() to convert special characters to HTML entities
and prevent XSS attacks.
Use trim() to remove extra spaces.
Display Errors:
Use variables like $nameErr to store error messages for each field.
Display these messages near the corresponding input fields.
Process Valid Data:
If all inputs are valid, proceed to process or save the data
Redirecting user
In PHP, you can redirect a user to another page or URL using the
header() function
Basic Syntax
header("Location: URL");
exit;
1. Redirect to Another Page on the Same Website
<?php
// Redirect to another page on the same server
header("Location: welcome.php");
exit;
?>
2. Redirect to an External URL
<?php
// Redirect to an external website
header("Location: https://www.example.com");
exit;
?>
3. Using SwiftMailer
SwiftMailer is another robust library for sending emails,
supporting SMTP, attachments, and HTML
Difference mail(), PhpMailer, SwiftMailer.