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

PHP Notes

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development, featuring server-side scripting, database connectivity, and extensive library support. It supports various data types including integers, floats, strings, booleans, arrays, objects, and NULL. The document also covers conditional statements, form validation, session management techniques, control structures, and type juggling in PHP.

Uploaded by

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

PHP Notes

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development, featuring server-side scripting, database connectivity, and extensive library support. It supports various data types including integers, floats, strings, booleans, arrays, objects, and NULL. The document also covers conditional statements, form validation, session management techniques, control structures, and type juggling in PHP.

Uploaded by

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

Q.

What is php and data types in php


PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language primarily designed for web
development. Originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994, PHP has evolved into a
powerful tool for building dynamic and interactive websites, web applications, and web services. Features of PHP:

1. Server-Side Scripting: PHP scripts are executed on the server, generating dynamic web content before being
sent to the client's web browser.

2. Embeddable: PHP code can be embedded within HTML documents, allowing for seamless integration of
dynamic content with static web pages.

3. Cross-Platform Compatibility: PHP is compatible with various operating systems, including Windows,
macOS, Linux, and Unix-like systems.

4. Extensive Library Support: PHP has a vast ecosystem of built-in functions and libraries for common tasks
such as database access, file manipulation, and string processing.

5. Database Connectivity: PHP provides support for connecting to various databases, including MySQL,
PostgreSQL, SQLite, and Oracle, making it suitable for building database-driven web applications.

6. Framework Support: PHP has numerous popular frameworks such as Laravel, Symfony, CodeIgniter, and
Zend Framework that streamline web development and promote code organization and reusability.

Data Types in PHP: PHP supports several data types, which are used to represent different kinds of values. Some of
the commonly used data types in PHP include:

1. Integer- An integer is a non-decimal number between -2,147,483,648 and 2,147,483,647.

Example: $age = 25;

2. Float (or Double) - A float is a number with a decimal point or a number in exponential form.

Example: $price = 99.99;

3. String- A string is a sequence of characters enclosed in single (' ') or double (" ") quotes.

Example: $name = "John Doe";

4. Boolean- Booleans have only two possible values: TRUE or FALSE. Often used in conditional statements.

Example: $is_logged_in = true;

5. Array-An array is a collection of values. Each value is assigned a key which can be numeric or associative. Example -

(Indexed Array):$colors = array("Red", "Green", "Blue");

(Associative Array): $student = array("name" => "Alice", "age" => 20);

6. Object- Objects are instances of classes that contain both data (properties) and functions (methods).

Example: class Car { public $color;

public function setColor($color) {

$this->color = $color; } }
$myCar = new Car();
$myCar->setColor("Red");

7. NULL- The NULL data type is used to represent a variable with no value. Example: $x = NULL;
Q. Explain the different conditional statements in PHP with suitable example

Conditional statements are used in PHP to make decisions and execute certain code blocks based on whether
a condition is true or false. This allows programs to respond dynamically to different inputs or situations.In
programming, decision-making is crucial—whether it’s checking a user’s login credentials, calculating a
grade based on marks, or determining which menu item a user selected. PHP offers several types of
conditional statements for handling such logic efficiently.

Types of Conditional Statements in PHP

1. if Statement- Executes a block of code only if the condition is true.

Syntax: if (condition) {

// code to execute }

Example: $age = 20;

if ($age >= 18) {


echo "You are eligible to vote."; }

2. if...else Statement- Executes one block of code if the condition is true, otherwise it executes
another block.

Syntax: if (condition) {

// code if condition is true


} else {
// code if condition is false }

Example: $marks = 45;

if ($marks >= 50) {


echo "Pass";
} else {
echo "Fail"; }

3. if...elseif...else Statement- Allows you to check multiple conditions one after another. Once a
true condition is found, its block executes, and the rest are skipped.

Syntax: if (condition1) {

// code if condition1 is true


} elseif (condition2) {
// code if condition2 is true
} else {
// code if none are true }

Example: $score = 72;

if ($score >= 90) {


echo "Grade A";
} elseif ($score >= 70) {
echo "Grade B";
} elseif ($score >= 50) {
echo "Grade C";
} else {
echo "Fail"; }
4. switch Statement- Used to compare one variable with multiple fixed values. More readable than
if...elseif when checking against many exact matches.

Syntax: switch (variable) {

case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block }

Example: $day = "Sunday";

switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Sunday":
echo "Weekend!";
break;
default:
echo "Midweek day"; }

Q. Explain From validation in PHP


Form validation in PHP is the process of verifying and validating user input submitted through HTML forms to ensure
that it meets certain criteria or requirements. This is crucial for maintaining the integrity and security of your web
application by preventing malicious or incorrect data from being processed.Steps for Form Validation in PHP:

1. HTML Form Creation: Create an HTML form with input fields for user data. Add appropriate HTML attributes
such as name, type, placeholder, and required for input fields.

2. Server-Side Validation: PHP script receives the form data submitted by the user. Validate each input field to
ensure it meets the specified criteria (e.g., required fields, valid email format, numeric values, etc.). Use
conditional statements and validation functions to check each input value. Sanitize user input to prevent SQL
injection, XSS attacks, and other security vulnerabilities.

3. Displaying Error Messages: If validation fails for any input field, display appropriate error messages next to
the corresponding fields. Use CSS to style error messages and provide visual feedback to users.

4. Repopulating Form Fields: If the form submission fails due to validation errors, repopulate the form fields
with the previously submitted values. This allows users to correct their mistakes without re-entering all the
data.

5. Handling Form Submission: If all input data passes validation, process the form submission according to your
application's logic (e.g., storing data in a database, sending email, etc.). Use appropriate error handling
techniques to deal with any unexpected errors during form processing.
Q. Illustrate the different type of Array used in PHP with suitable example

An array in PHP is a data structure that allows you to store multiple values in a single variable. Arrays are
especially useful when you need to manage lists of data, such as user names, scores, product details, etc.PHP
supports three main types of arrays, each suited for different scenarios:

1. Indexed Array – stores values with numeric indexes.


2. Associative Array – uses named keys (strings) instead of numeric indexes.
3. Multidimensional Array – an array containing one or more arrays (useful for tabular or grouped
data).

Types of Arrays in PHP

1. Indexed Array- Elements are stored with automatically assigned numeric indexes (starting from
0).Ideal for simple lists like numbers, names, etc.

Syntax: $colors = array("Red", "Green", "Blue");

Example: $fruits = array("Apple", "Banana", "Cherry");

echo $fruits[1]; // Output: Banana

2. Associative Array- Elements are stored with custom named keys instead of numeric indexes.Best for
representing key-value pairs like names and ages, product and prices, etc.

Syntax: $person = array("name" => "John", "age" => 25, "gender" => "Male");

Example: $student = array("roll_no" => 101, "name" => "Amit", "marks" => 88);

echo $student["name"]; // Output: Amit

3. Multidimensional Array- An array that contains one or more arrays as elements. Useful for
representing matrices, tables, or complex records.

Syntax: $students = array(

array("Amit", 85, "A"),


array("Sneha", 78, "B"),
array("Ravi", 92, "A+") );

Access Example:

echo $students[0][0]; // Output: Amit


echo $students[1][2]; // Output: B

Example with Associative Keys Inside:

php
CopyEdit
$users = array(
"user1" => array("name" => "Aman", "email" => "[email protected]"),
"user2" => array("name" => "Rita", "email" => "[email protected]")
);

echo $users["user1"]["email"]; // Output: [email protected]


Q. what is form validation and sanitization how it is performed in PHP.

When users submit data via an HTML form (e.g., login, registration, contact forms), it is important to
validate and sanitize the data before processing it. This protects the application from malicious input,
syntax errors, and potential security threats such as SQL injection and cross-site scripting (XSS).

 Form Validation- Form validation is the process of checking whether the user-input data meets
specific rules or conditions (e.g., not empty, valid email format, numeric values only, etc.).Form
validation can be of two types:

 Client-side validation – done using JavaScript before sending the data to the server.
 Server-side validation – done using PHP after the data is submitted to the server (more secure and
reliable).

 Form Sanitization-Sanitization is the process of cleaning and filtering input data to ensure
it is safe for storage or display. It removes unwanted characters or harmful code from the
input.Sanitization is essential for security, especially when handling user input that will be used
in databases or output to HTML pages.

How Validation and Sanitization are performed in PHP


1. Example of Server-Side Validation and Sanitization
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];

// Validation
if (empty($name)) {
echo "Name is required.";
} else {
// Sanitization
$name = htmlspecialchars(trim($name));
}

if (empty($email)) {
echo "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
} else {
// Sanitization
$email = filter_var($email, FILTER_SANITIZE_EMAIL);}}

2. Example Using Full Validation and Sanitization


$username = $password = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validation
if (!empty($_POST["username"])) {
// Sanitization
$username = htmlspecialchars(strip_tags(trim($_POST["username"])));
} else {
echo "Username is required."; }

if (!empty($_POST["password"])) {
// Sanitization
$password = htmlspecialchars(strip_tags(trim($_POST["password"])));
} else {
echo "Password is required."; } }

Q. Explain different session management system techniques used in PHP.

Session management refers to the technique of storing and maintaining user-specific data across
multiple pages of a web application. HTTP is a stateless protocol, meaning it doesn’t retain user information
across requests. Session management helps overcome this limitation and enables features like login systems,
shopping carts, and user preferences. In PHP, session management is mainly done using:-
Cookies, Sessions, URL rewriting, Hidden form fields. Each of these techniques serves a similar purpose
but is implemented differently based on the level of security, ease of use, and storage capacity required.

1. Cookies- A cookie is a small piece of data stored on the client’s browser. It stores information like user
ID or preferences that can be read by the server on future requests. Cookies are not very secure (as they are
stored on the client side), so they shouldn't be used for sensitive data.

Syntax to set and retrieve a cookie: // Set a cookie (name, value, expiry time)

setcookie("username", "John", time() + 3600); // 1 hour

// Retrieve cookie
echo $_COOKIE["username"];

2. Sessions- A session is a way to store information (in variables) to be used across multiple pages. Unlike
cookies, session data is stored on the server, making it more secure. A unique session ID is stored in a
cookie or passed via the URL.

Syntax to start and use a session:

// Start session
session_start();

// Set session variables


$_SESSION["user"] = "John";

// Retrieve session variable


echo $_SESSION["user"];

3. URL Rewriting- Used when cookies are disabled in the browser. The session ID is appended to the
URL manually or using PHP’s built-in support.Less secure because the session ID is visible in the URL and
can be shared or stolen easily.Example:

<a href="profile.php?PHPSESSID=<?php echo session_id(); ?>">Profile</a>

 PHP automatically rewrites URLs if session.use_trans_sid is enabled in php.ini.

4. Hidden Form Fields- Hidden fields in HTML forms are used to pass session-related data from one
page to another.Works only with form submissions and is not suitable for secure or complex session
management.

Example:

<form action="nextpage.php" method="post">


<input type="hidden" name="userid" value="12345">
<input type="submit" value="Next">
</form>

PHP retrieval: $userid = $_POST["userid"];


Q. Explain control structure in php
Control structures in PHP are constructs that allow you to control the flow of execution in your code based on
certain conditions. These structures enable you to make decisions, iterate over data, and execute code blocks
conditionally. PHP supports various control structures, including conditional statements, loop statements, and
branching statements.

1. Conditional Statements:

a. If Statement: The if statement allows you to execute a block of code if a specified condition is true.

if (condition) {

// Code to execute if condition is true }

b. If-Else Statement: The if-else statement extends the if statement by allowing you to execute one block of code if
the condition is true and another block of code if the condition is false.

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false }

2. Loop Statements:

a. For Loop: The for loop allows you to iterate over a block of code a specified number of times.

for ($i = 0; $i < 5; $i++) {

// Code to execute in each iteration }

b. While Loop: The while loop executes a block of code as long as a specified condition is true.

while (condition) {

// Code to execute as long as condition is true }

c. Do-While Loop: The do-while loop is similar to the while loop, but it always executes the block of code at least
once before checking the condition.

do {

// Code to execute at least once

} while (condition);

3. Branching Statements:

a. Break Statement: The break statement is used to exit the current loop or switch statement.

b. Continue Statement: The continue statement is used to skip the rest of the current iteration of a loop and
proceed to the next iteration.

c. Switch Statement: The switch statement allows you to execute one of many blocks of code based on the value of
an expression.

These control structures in PHP provide powerful mechanisms for controlling the flow of execution in your scripts,
enabling you to write more dynamic and flexible code.
Q. Explain types of juggling and type casting in php

In PHP, juggling refers to the automatic conversion of values between different data types in certain contexts. This
can happen implicitly during operations or comparisons when PHP attempts to interpret the operands as compatible
types. Type casting, on the other hand, involves explicitly converting values from one data type to another.

 Types of Juggling:

1. Numeric Juggling: PHP automatically converts strings containing numeric values to numbers when used in
arithmetic operations.

$str = "10";

$num = $str + 5; // $num will be 15 (string "10" converted to integer 10)

2. String Juggling: PHP automatically converts non-string values to strings when used in string contexts, such as
concatenation with the “. “operator.

$num = 10;

$str = "Value: " . $num; // $str will be "Value: 10" (integer 10 converted to string "10")

3. Boolean Juggling: PHP automatically converts values to boolean (true or false) in certain contexts, such as
conditional statements (if, while, etc.) and logical operations (&&, ||, !).

$num = 10;

if ($num) { // This block will execute because $num evaluates to true (non-zero values are considered true) }

 Type Casting: Type casting involves explicitly converting values from one data type to another using casting
operators or functions.

1. Implicit Type Casting: PHP automatically performs some type conversions when necessary, such as
converting between strings and numbers.

$str = "10";

$num = $str + 5; // Implicitly converts string "10" to integer 10

2. Explicit Type Casting: PHP provides casting operators and functions to explicitly convert values between data
types.

 (int) or (integer): Converts a value to an integer.

 (float) or (double): Converts a value to a floating-point number.

 (string): Converts a value to a string.

 (bool) or (boolean): Converts a value to a boolean.

 (array): Converts a value to an array.

 (object): Converts a value to an object.

$str = "10";

$num = (int)$str; // Explicitly casts string "10" to integer 10

3. Type Juggling Functions: PHP also provides functions like intval(), floatval(), strval(), and boolval() to
explicitly convert values to specific data types.

$str = "10";

$num = intval($str); // Explicitly converts string "10" to integer 10


Q. Explain php GET and POST method
In PHP, the GET and POST methods are used to send data from a client (such as a web browser) to a server. They are
both HTTP methods, but they differ in how they transmit data and the scenarios in which they are typically used.

GET Method:

1. Data Transmission:

 Data is appended to the URL as query parameters.

 Data is visible in the URL, which means it is less secure and has a length limit imposed by the
browser.

 Example: http://example.com/page.php?name=John&age=30

2. Usage:

 Generally used for requests that retrieve data from the server.

 Suitable for non-sensitive data that doesn't need to be hidden from the user.

 Often used for search queries, pagination, and navigation.

3. Example in PHP:

<?php

$name = $_GET['name'];

$age = $_GET['age'];

echo "Hello, $name! You are $age years old.";

?>

POST Method:

1. Data Transmission:

 Data is sent in the body of the HTTP request.

 Data is not visible in the URL, which makes it more secure.

 No inherent length limit for data transmission.

2. Usage:

 Generally used for requests that modify or submit data to the server.

 Suitable for sensitive data like passwords or personal information.

 Often used for form submissions, file uploads, and other actions that change server state.

3. Example in PHP:

<?php

$name = $_POST['name'];

$age = $_POST['age'];

echo "Hello, $name! You are $age years old.";

?>
Q. Explain Magic constants and const keyword

 Magic Constants:

Magic constants are predefined constants in PHP that change based on their context. They provide information
about the current script, such as file paths, line numbers, and function names. Magic constants are always available
and prefixed with double underscores (__).

Some commonly used magic constants include:

1. __FILE__: The full path and filename of the current script.

2. __DIR__: The directory of the current script.

3. __LINE__: The current line number in the script.

4. __FUNCTION__: The name of the current function.

5. __CLASS__: The name of the current class.

6. __METHOD__: The name of the current class method.

7. __NAMESPACE__: The name of the current namespace.

Example usage:

echo __FILE__; // Outputs: /path/to/current/script.php

echo __LINE__; // Outputs: 5

echo __FUNCTION__; // Outputs: functionName

 const Keyword:

The const keyword is used to define class constants in PHP. Class constants are similar to variables, but their values
cannot be changed once they are defined. Class constants are scoped within the class and accessed using the class
name without the need for an object instance.

Example usage: class MyClass {

const PI = 3.14;

const VERSION = "1.0";

public function printPi() {

echo self::PI; } }

echo MyClass::PI; // Outputs: 3.14

echo MyClass::VERSION; // Outputs: 1.0

Key points about class constants defined using the const keyword:

1. They are declared using the const keyword inside a class.

2. They are accessible without creating an object instance of the class.

3. They cannot be changed or modified after they are defined.

4. They are case-sensitive.

Using class constants provides a way to define and use values that are associated with a class and should not be
changed during the script's execution. They help improve code readability and maintainability by providing
meaningful names for constants used within a class.
Q. Explain PHP function and array

1. PHP Functions: Functions in PHP are blocks of reusable code that perform a specific task. They encapsulate
functionality and can accept input parameters and return values. Functions help in organizing code, promoting code
reuse, and improving maintainability.

 Defining Functions: function functionName($parameter1, $parameter2) {

// Function body

return $parameter1 + $parameter2;

 Calling Functions: $result = functionName(10, 20);

echo $result; // Outputs: 30

Key Points:

1. Functions are defined using the function keyword, followed by the function name and a parameter list (if
any).

2. Functions may accept zero or more parameters, which are placeholders for values passed to the function.

3. Functions may return a value using the return statement.

4. PHP supports both named functions and anonymous functions (also known as closures).

2. PHP Arrays: Arrays in PHP are versatile data structures used to store multiple values in a single variable. They can
hold elements of different data types, such as integers, strings, and even other arrays. Arrays in PHP can be indexed
numerically or associatively.

Numerically Indexed Arrays: $numbers = array(10, 20, 30);

Associative Arrays:

$person = array(

"name" => "John",

"age" => 30,

"city" => "New York"

);

Accessing Array Elements:

echo $numbers[0]; // Outputs: 10

echo $person["name"]; // Outputs: John

Key Points:

1. Arrays in PHP can be created using the array() constructor or the shorthand [] syntax introduced in PHP 5.4.

2. Arrays can be numerically indexed (with integer keys) or associatively indexed (with string keys).

3. Arrays can be nested, allowing for the creation of multidimensional arrays.

4. PHP provides numerous functions for manipulating arrays, such as array_push(), array_pop(), array_merge(),
array_keys(), and array_values().
Q. Explain MySQL in PHP

MySQL is a popular open-source relational database management system (RDBMS) widely used with PHP for storing
and managing structured data. PHP provides built-in functions and extensions for interacting with MySQL databases,
making it easy to create dynamic web applications that store and retrieve data from a MySQL database.

Interacting with MySQL in PHP:

1. Connecting to MySQL Database: Use the mysqli_connect() or PDO::__construct() function to establish a


connection to a MySQL database server.

$conn = mysqli_connect($servername, $username, $password, $dbname);

2. Executing SQL Queries: Use the mysqli_query() or PDO::query() function to execute SQL queries against the
connected database.

$result = mysqli_query($conn, "SELECT * FROM table_name");

3. Fetching Data: Use functions like mysqli_fetch_assoc(), mysqli_fetch_array(), or PDOStatement::fetch() to


retrieve data from query results.

while ($row = mysqli_fetch_assoc($result)) {

echo $row['column_name']; }

4. Inserting, Updating, and Deleting Data: Use SQL INSERT, UPDATE, and DELETE statements with
mysqli_query() or prepared statements with mysqli_prepare() and mysqli_stmt_execute() for data
manipulation operations.

mysqli_query($conn, "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");

5. Handling Errors: Use functions like mysqli_error() or PDO::errorInfo() to handle database errors and
exceptions.

if (!$result) {

echo "Error: " . mysqli_error($conn); }

6. Closing Database Connection: Always close the database connection using mysqli_close() or PDO::close()
after performing database operations.

mysqli_close($conn);

Prepared Statements: Prepared statements are an advanced feature in MySQL that allow for efficient execution of
parameterized queries. They prevent SQL injection attacks and improve performance by pre-compiling SQL queries.

Security Considerations: When interacting with MySQL databases in PHP, it's essential to consider security best
practices to prevent SQL injection attacks. Use prepared statements or properly escape user input to sanitize data
before executing SQL queries.
Q. write a short note on exception handling in PHP

Exception handling in PHP allows you to handle runtime errors in a more controlled way, rather than
letting the application crash or display generic error messages. By using exceptions, you can catch and
respond to errors gracefully, providing a better user experience and more robust applications.An exception
is an object that describes an error or an unexpected event that occurs during the execution of a program.
Exceptions can be thrown (triggered) and caught (handled) using specific PHP keywords.

Key Concepts:

 Throwing an exception: When an error occurs, an exception is "thrown".


 Catching an exception: The thrown exception is caught and handled in a catch block.

1. Basic Syntax
try {
// Code that may throw an exception
if ($some_error_condition) {
throw new Exception("Something went wrong!");
}
} catch (Exception $e) {
// Code to handle the exception
echo "Caught exception: " . $e->getMessage();
}

 try block: Contains the code that might throw an exception.


 throw keyword: Used to trigger an exception.
 catch block: Used to handle the exception if it is thrown. It catches the exception object and allows
you to access its properties and methods.

2. Exception Methods

 getMessage(): Returns the error message.


 getCode(): Returns the exception code.
 getFile(): Returns the file where the exception was thrown.
 getLine(): Returns the line number where the exception was thrown.

3. Custom Exception Handling- You can create custom exception classes to handle specific types of
errors.

4. Multiple Catch Blocks- You can catch multiple types of exceptions using multiple catch blocks.

Concept Description

try block Contains the code that may throw an exception.

throw keyword Used to throw an exception when a certain condition is met.

catch block Used to handle the exception thrown and perform error handling.

Custom exceptions Allows the creation of user-defined exceptions with custom behavior.
Q. explain variable scope in PHP.

Definition: Variable scope in PHP refers to the context or region of a program in which a variable is defined
and can be accessed or modified. It defines the visibility and lifetime of a variable. PHP supports several
types of scope to control how variables behave in different parts of a program.

1. Local Scope- A variable declared within a function is considered to be in local scope. It is accessible
only within that function. Once the function execution is complete, the local variable is destroyed (i.e., it
ceases to exist). Local variables are independent of variables outside the function, even if they have the
same name. Use Case: Used when a variable is needed only for a specific operation within a function and
doesn't affect the rest of the program.

2. Global Scope- Variables declared outside of any function or class are said to be in the global scope.
These variables are available throughout the script, but not inside functions or methods directly.To
access global variables inside a function, PHP requires the use of:

o The global keyword, or


o The superglobal array $GLOBALS.

Use Case: Used when a variable needs to be shared across multiple functions or parts of a script.

3. Static Scope- PHP allows you to define a variable as static inside a function. A static variable is
initialized only once, and its value persists across multiple calls to the function. It maintains its state
between function calls, unlike a regular local variable which is reinitialized each time.

Use Case: Useful for keeping track of information across multiple function executions, such as counters.

4. Function Parameters (Argument Scope)

 When a function is called, you can pass values to it using parameters.


 These parameters act like local variables inside the function.
 By default, they are passed by value (a copy of the variable is passed).
 You can pass variables by reference using the & symbol, which allows the function to modify the
original variable.

Use Case: Enables data to be sent into a function for processing, either as a copy or for direct modification.

5. Superglobal Variables

 PHP provides several built-in arrays known as superglobals, such as:


o $_POST, $_GET, $_SESSION, $_COOKIE, $_SERVER, etc.
 These are available in all scopes (global and local) without needing the global keyword.

Use Case: Used for handling HTTP requests, server data, session management, etc.

You might also like