PHP
PHP, which stands for "PHP: Hypertext Preprocessor," is a widely-used open-source server-side
scripting language primarily designed for web development. It allows developers to create
dynamic and interactive web pages efficiently.
History of PHP
Origins
• Creation: PHP was created in 1994 by Rasmus Lerdorf, initially as a set of Common
Gateway Interface (CGI) scripts to manage his personal website. The original name was
"Personal Home Page Tools" (PHP Tools).
• Evolution: In 1995, Lerdorf released the source code to the public, leading to further
development and the introduction of PHP/FI (Personal Home Page/Forms Interpreter),
which included features for handling forms and database interactions.
Major Versions
• PHP 3 (1997): This version marked a significant milestone, introducing object-oriented
programming support and a more robust architecture. It attracted a larger developer
community and laid the foundation for future enhancements.
• PHP 4 (2000): With the introduction of the Zend Engine, PHP 4 improved performance
and reliability. This version became widely adopted for web applications due to its
enhanced capabilities.
• PHP 5 (2004): A major overhaul that introduced advanced object-oriented programming
features, improved error handling, and support for web services like SOAP. PHP 5
solidified PHP's reputation as a powerful web development tool.
• PHP 7 (2015): This version brought significant performance improvements—up to twice
as fast as PHP 5—and introduced new features such as scalar type declarations and the null
coalescing operator
• PHP 8 (2020): The latest version introduced Just-In-Time (JIT) compilation for enhanced
performance, along with new features like union types and attributes, further modernizing
the language.
Why Choose PHP?
Advantages
• Open Source: PHP is free to use and has a large community contributing to its continuous
improvement. This openness fosters innovation and provides extensive resources for
developers.
• Ease of Use: With a syntax similar to C and Perl, PHP is relatively easy to learn, making
it accessible for beginners while still powerful enough for experienced developers.
• Wide Adoption: PHP powers millions of websites and applications worldwide, including
major platforms like WordPress, Drupal, and Joomla. Its widespread use ensures a wealth
of libraries, frameworks, and resources.
• Database Integration: PHP seamlessly integrates with various databases such as MySQL,
PostgreSQL, and Oracle, making it an excellent choice for data-driven applications.
• Versatility: Beyond web development, PHP can be used for command-line scripting and
desktop application development.
• Strong Community Support: The active community offers extensive documentation,
forums, and tutorials, making it easier for developers to find help and share knowledge.
• Performance Improvements: Recent versions have significantly improved performance
through optimizations like JIT compilation in PHP 8, making it suitable for high-traffic
applications.
Installing and configuring PHP
Installing and configuring PHP is a crucial step for setting up a web server to handle dynamic
web pages. Here’s a detailed, step-by-step guide to installing and configuring PHP, particularly for
Windows.
Step 1: Install PHP
Option 1: Using XAMPP (Preferred for beginners)
XAMPP is a free and open-source cross-platform web server solution that includes Apache,
MySQL, PHP, and Perl. It's the easiest way to set up PHP quickly.
1. Download XAMPP:
o Go to the official XAMPP website.
o Choose the appropriate version for your operating system (Windows in this case)
and download it.
2. Install XAMPP:
o Run the installer and follow the installation instructions.
o During installation, you’ll be asked to select components. Ensure PHP is checked
along with Apache and MySQL (optional if you're using databases).
o Finish the installation process.
3. Start XAMPP Control Panel:
o After installation, open the XAMPP Control Panel.
o Start the Apache module (this includes PHP).
4. Verify Installation:
o Open a browser and go to http://localhost/.
o If XAMPP is installed correctly, you will see the XAMPP welcome page.
5. Create a PHP Info File:
o Go to the XAMPP installation directory (usually C:\xampp\htdocs\).
o Create a new file named info.php with the following content:
<?php
phpinfo();
?>
o Save the file and navigate to http://localhost/info.php in your browser.
o This should display PHP configuration details, verifying that PHP is installed
correctly.
Option 2: Manual PHP Installation (Advanced)
If you want to install PHP manually without XAMPP, follow these steps:
1. Download PHP:
o Go to the official PHP website.
o Download the latest stable version of PHP for Windows (Thread Safe version is
recommended for running with Apache).
2. Extract PHP:
o Extract the downloaded zip file to a location on your system (e.g., C:\php\).
3. Add PHP to Windows PATH:
o Right-click on “This PC” (or "My Computer") and choose “Properties”.
o Click on “Advanced system settings” and then “Environment Variables”.
o Under “System variables,” find the Path variable, select it, and click “Edit”.
o Click “New” and add the path to your PHP folder (e.g., C:\php).
o Click OK to close the dialog boxes.
Configure PHP:
PHP configuration is necessary to customize and optimize how PHP interacts with the server,
databases, and other resources in a specific environment. Proper configuration ensures that PHP
operates efficiently, securely, and according to the needs of the application being run.
• Open the C:\php\ directory.
• Find the php.ini-development file and rename it to php.ini.
• Open php.ini with a text editor and configure important settings:
o Enable extensions: Uncomment extensions you need (e.g., extension=curl,
extension=mysqli).
o Set timezone: Search for date.timezone and set it according to your timezone.
Advantages of PHP Over Other Scripting Languages
1. Ease of Use: PHP has a simple syntax that is easy to learn for beginners, especially those
familiar with C or JavaScript.
2. Integration with HTML: PHP can be embedded directly into HTML code, allowing for
dynamic content generation without complex setups.
3. Wide Database Support: PHP supports various databases (MySQL, PostgreSQL,
SQLite), making it versatile for data-driven applications.
4. Open Source and Community Support: Being open-source means it is free to use, with
a large community providing extensive resources, libraries, and frameworks (like Laravel
and Symfony).
5. Cross-Platform Compatibility: PHP runs on multiple platforms (Windows, Linux,
macOS), making it flexible for different server environments.
6. Performance: Recent versions of PHP have significantly improved performance through
optimizations like Just-In-Time (JIT) compilation.
Creating a Simple PHP Script
PHP scripts are written inside a file with a .php extension. They are executed on the server when
a user requests the corresponding URL.
Basic PHP Script Example
<?php
// This is a simple PHP script that prints "Hello, World!"
echo "Hello, World!";
?>
How It Works:
• The <?php ?> tags are used to embed PHP code inside HTML or to write standalone PHP
scripts.
• The echo statement outputs text or variables to the browser.
• In this case, when the script is accessed via a web browser, it will display Hello, World!.
Creating a PHP Script with Error Handling
In PHP, you can handle errors using a variety of methods. PHP has built-in error reporting
mechanisms, and you can also create custom error handling functions.
Types of Errors in PHP:
1. Parse Errors (Syntax Errors):
o These occur when PHP fails to parse the script due to a syntax mistake.
o Example:
<?php
echo "Hello, World!"
?>
This will result in a parse error because there’s no semicolon ; at the end of the echo
statement.
Fatal Errors:
• These happen when PHP cannot execute the script due to a serious issue, such as calling
an undefined function.
• Example
<?php
myUndefinedFunction();
?>
This will result in a fatal error since the function myUndefinedFunction() doesn’t exist.
Warnings:
• Warnings occur when there is a problem with the script, but PHP can still continue
executing.
• Example:
<?php
include("non_existing_file.php");
echo "This will still be printed!";
?>
This will generate a warning because the file non_existing_file.php doesn’t exist, but the script
will still run.
Notices:
• Notices are minor issues, like using an undefined variable, but the script continues
execution.
• Example:
<?php
echo $undefined_variable;
?>
This will generate a notice saying $undefined_variable is not defined, but the script will execute.
Handling Errors in PHP
1. Using try and catch for Exception Handling
PHP provides a way to handle exceptions using try, catch, and throw blocks. This is used when
you want to manage runtime errors more gracefully.
<?php
function divide($numerator, $denominator) {
if ($denominator == 0) {
throw new Exception("Division by zero is not allowed.");
return $numerator / $denominator;
try {
echo divide(10, 0);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage();
?>
Explanation:
• The throw statement generates an exception when division by zero is attempted.
• The try block contains code that might throw an exception.
• The catch block handles the exception and retrieves the error message using $e-
>getMessage().
Data Types
In PHP, data types define the kind of data that can be stored and manipulated within a script.
PHP is a loosely typed language, meaning it automatically converts data types when needed.
Variables
Variables are used to store data. In PHP, variables start with the $ symbol followed by the
variable name. PHP automatically converts the type based on the assigned value.
Example:
<?php
$name = "John"; // String variable
$age = 25; // Integer variable
$height = 5.9; // Float variable
$isStudent = true; // Boolean variable
echo $name; // Output: John
?>
• Variables are case-sensitive ($name is different from $Name).
• No need to declare the type explicitly; PHP does it dynamically based on the value
assigned.
Scope of variable
Local Scope
A variable defined within a function has a local scope, meaning it can only be accessed inside
that function. Once the function execution is complete, the local variable is destroyed.
Example of Local Scope
<?php
function myFunction() {
$localVar = "I am local"; // Local variable
echo $localVar; // Outputs: I am local
myFunction();
echo $localVar; // Generates an error: Undefined variable
?>
Output
I am local
Warning: Undefined variable $localVar in /home/user/scripts/code.php on line 8
In this example, $localVar is accessible only within myFunction. Attempting to access it
outside results in an error.
Global Scope
A variable declared outside any function has a global scope. This means it can be accessed
anywhere in the script, but not directly from within functions unless specified.
Example of Global Scope
<?php
$globalVar = "I am global"; // Global variable
function myFunction() {
global $globalVar; // Accessing global variable
echo $globalVar; // Outputs: I am global
}
myFunction();
echo $globalVar; // Outputs: I am global
?>
Static Scope
Static variables are declared using the static keyword inside a function. Unlike local variables,
static variables retain their value between function calls.
Example of Static Scope
<?php
function myFunction() {
static $count = 0; // Static variable
echo $count;
$count++;
myFunction(); // Outputs: 0
myFunction(); // Outputs: 1
myFunction(); // Outputs: 2
?>
In this case, $count retains its value across multiple calls to myFunction, demonstrating how
static variables can be useful for maintaining state.
Types of Data types
1. Strings
Strings are sequences of characters. In PHP, strings can be defined using single quotes (') or
double quotes (").
Example:
<?php
$greeting = "Hello, World!";
echo $greeting; // Output: Hello, World!
?>
➢ Common String Functions:
1. strlen($string): Returns the length of the string.
<?php
$str = "Hello";
echo strlen($str); // Output: 5
?>
2. strtoupper(): Converts a string to uppercase.
<?php
$string = "hello, world!";
echo strtoupper($string); // Outputs: HELLO, WORLD!
?>
3. strtolower(): Converts a string to lowercase.
<?php
$string = "HELLO, WORLD!";
echo strtolower($string); // Outputs: hello, world!
?>
4. strrev(): Reverses a string.
<?php
$string = "Hello";
echo strrev($string); // Outputs: olleH
?>
5. str_replace(): Replaces all occurrences of a search string with a replacement string.
<?php
$string = "Hello, World!";
echo str_replace("World", "PHP", $string); // Outputs: Hello, PHP!
?>
2. Numbers
PHP has two types of numbers:
• Integers: Whole numbers, both positive and negative.
• Floats (or Doubles): Decimal numbers.
Example:
<?php
$num1 = 10; // Integer
$num2 = 5.5; // Float
echo $num1 + $num2; // Output: 15.5
?>
3. Arrays
Arrays are used to store multiple values in a single variable. PHP supports different types of
arrays:
• Indexed Arrays: Use numeric keys (indexes).
• Associative Arrays: Use named keys (strings).
• Multidimensional Arrays: Arrays within arrays.
• Indexed Arrays: Indexed arrays use numeric indices to access their elements.
Example:
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo "First fruit: " . $fruits[0]; // Outputs: First fruit: Apple
?>
• Associative Arrays: Associative arrays use named keys that you assign to them.
Example:
<?php
$person = array(
"first_name" => "John",
"last_name" => "Doe",
"age" => 30
);
echo "Name: " . $person["first_name"] . " " . $person["last_name"]; // Outputs: Name: John
Doe
?>
• Multidimensional Arrays: Multidimensional arrays contain one or more arrays within them.
Example:
<?php
$contacts = array(
array("John", "Doe", 30),
array("Jane", "Smith", 25),
array("Sam", "Brown", 22)
);
echo $contacts[1][0]; // Outputs: Jane
?>
Common Array Functions
PHP provides a variety of built-in functions to manipulate arrays. Here are some commonly
used functions with examples:
1. count(): Counts all the elements in an array.
Example:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo "Number of fruits: " . count($fruits); // Outputs: Number of fruits: 3
?>
2. array_push(): Adds one or more elements to the end of an array.
Example:
<?php
$fruits = ["Apple", "Banana"];
array_push($fruits, "Cherry");
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry )
?>
3. array_pop(): Removes the last element from an array and returns it.
Example:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
array_pop($fruits);
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana )
?>
4. array_slice(): Extracts a portion of an array.
Example:
?php
$fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
print_r(array_slice($fruits, 1, 3));
// Outputs: Array ( [0] => Banana [1] => Cherry [2] => Date )
?>
4. Booleans
Booleans represent two possible states: true or false. They are often used in conditional
statements to control the flow of the program.
Example:
<?php
$isLoggedIn = true;
if ($isLoggedIn) {
echo "Welcome, User!"; // Output: Welcome, User!
?>
Booleans are automatically converted to 1 (true) or an empty string "" (false) when echoed.
5. NULL
NULL is a special data type representing a variable with no value. A variable is considered
NULL if it has been assigned the constant NULL or hasn't been assigned any value.
Example:
<?php
$var = NULL;
if (is_null($var)) {
echo "Variable is NULL"; // Output: Variable is NULL
?>
• is_null($var) checks if a variable is NULL.
Type Switching and Casting
PHP allows switching between data types dynamically, but you can also explicitly cast data types
to ensure they match what is needed.
Example of Type Casting:
<?php
$var = "100"; // String value
$num = (int)$var; // Cast string to integer
echo $num; // Output: 100
?>
Common Type Casts:
• (int) or (integer): Cast to integer.
• (bool) or (boolean): Cast to boolean.
• (float): Cast to float.
• (string): Cast to string.
<?php
$var = "10";
echo var + 5; // "10" (string) is automatically converted to 10 (integer)
// Output: 15
?>
Constants
Constants are values that do not change during the execution of the script. They are defined using
the define() function and are accessed without the $ symbol.
Example:
<?php
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Output: MyWebsite
?>
Constants are case-sensitive by default, but you can make them case-insensitive by passing true as
the third argument in define():
<?php
define("GREETING", "Hello", true);
echo greeting; // Output: Hello
?>
Control Statements
Control structures in PHP allow to dictate the flow of execution in their programs. This includes
decision-making structures like if, else, and switch, as well as looping structures such as while, for,
and foreach. Additionally, control flow can be altered using continue and break statements.
1. Conditional Statements
➢ if Statement: The if statement in PHP is a fundamental control structure that allows you to
execute a block of code based on whether a specified condition evaluates to true.
Syntax:
if (condition) {
// Code to be executed if condition is true
}
How It Works
1. Condition Evaluation: The expression inside the parentheses is evaluated. If it returns true, the
code block within the curly braces {} is executed.
2. Skipping Execution: If the condition evaluates to false, the code block is skipped.
Examples
<?php
$number = 5;
if ($number > 0) {
echo "The number is positive.";
}
?>
➢ If-else Statement: The if...else statement in PHP is a fundamental control structure that allows
developers to execute different blocks of code based on whether a specified condition is true
or false. This enables the creation of dynamic and responsive applications.
Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
How It Works
1. Condition Evaluation: The expression inside the parentheses is evaluated.
2. Execution:
• If the condition evaluates to true, the code block following the if statement is executed.
• If the condition evaluates to false, the code block following the else statement is executed
Example
<?php
$number = 4;
if ($number % 2 == 0) {
echo "The number is even.";
} else {
echo "The number is odd.";
}
?>
➢ Else-if Statement: The elseif statement in PHP is a control structure that allows you to check
multiple conditions in a sequential manner. It is used in conjunction with
the if and else statements to create more complex decision-making processes.
Syntax
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if both condition1 and condition2 are false
}
How It Works
1. Condition Evaluation: The first condition in the if statement is evaluated. If it returns true,
the corresponding block of code executes.
2. Subsequent Conditions: If the first condition is false, the next elseif condition is evaluated.
This process continues until a true condition is found or all conditions are checked.
3. Fallback: If none of the conditions are true, the code in the else block (if present) will execute.
Example:
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} elseif ($score >= 60) {
echo "Grade: D";
} else {
echo "Grade: F";
?>
➢ Switch Statement: The switch statement in PHP is a control structure that allows you to
execute different blocks of code based on the value of a variable or expression. This can be
particularly useful when you have multiple conditions to evaluate, making the code more
readable compared to using multiple if...else statements.
Syntax
switch (expression) {
case label1:
// Code block to execute if expression matches label1
break;
case label2:
// Code block to execute if expression matches label2
break;
// Additional cases...
default:
// Code block to execute if no cases match
}
How It Works
1. Expression Evaluation: The expression is evaluated once.
2. Case Matching: The value of the expression is compared against the values of each case.
3. Execution: If a match is found, the corresponding block of code is executed.
4. Break Statement: The break keyword exits the switch block, preventing fall-through to
subsequent cases.
5. Default Case: The default case runs if none of the specified cases match
<?php
$favColor = "blue";
switch ($favColor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Logical Operators
Logical operators in PHP are used to combine conditional statements and evaluate boolean
expressions. They allow you to create complex conditions by combining multiple conditions
together. Here’s an overview of the main logical operators in PHP, along with examples to illustrate
their usage.
1. Logical AND Operator (&& or and)
The AND operator evaluates to true only if both operands are true. If either operand is false, the
result is false.
Example:
<?php
$x = 5;
$y = 10;
if ($x > 0 && $y > 0) {
echo "Both conditions are true!"; // This will execute
} else {
echo "At least one condition is false.";
}
?>
2. Logical OR Operator (|| or or): The OR operator evaluates to true if at least one of its operands
is true. It returns false only when both operands are false.
Example:
<?php
$x = -5;
$y = 10;
if ($x > 0 || $y > 0) {
echo "At least one condition is true!"; // This will execute
} else {
echo "Both conditions are false.";
}
?>
3. Logical NOT Operator (!): The NOT operator reverses the logical state of its operand. If the
condition is true, it becomes false, and vice versa.
Example:
<?php
$isRaining = false;
if (!$isRaining) {
echo "It's not raining!"; // This will execute
} else {
echo "It's raining!";
}
?>
4. Logical XOR Operator (xor): The XOR (exclusive OR) operator evaluates to true if exactly
one of its operands is true. If both are true or both are false, it returns false.
Example:
<?php
$x = true;
$y = false;
if ($x xor $y) {
echo "Exactly one condition is true (XOR)!"; // This will execute
} else {
echo "Both conditions are either true or false.";
}
?>
Loops
Loops are used to repeat a block of code multiple times based on a given condition. PHP provides
several types of loops to handle different scenarios, including while loops, for loops, do…while
loops, and foreach loops.
for Loop
PHP for loop is used when you know exactly how many times you want to iterate through a block
of code. It consists of three expressions:
• Initialization: Sets the initial value of the loop variable.
• Condition: Checks if the loop should continue.
• Increment/Decrement: Changes the loop variable after each iteration.
Syntax
for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed
}
Example: Printing numbers from 1 to 5 using for loop.
<?php
// Code to illustrate for loop
for ($num = 1; $num <= 5; $num += 1) {
echo $num . " ";
}
?>
while Loop
The while loop is also an entry control loop like for loops. It first checks the condition at the start
of the loop and if its true then it enters into the loop and executes the block of statements, and goes
on executing it as long as the condition holds true.
Syntax
while ( condition ) {
// Code is executed
}
Example: Printing numbers from 1 to 5.
<?php
$num = 1;
while ($num <= 5) {
echo $num . " ";
$num++;
}
?>
do-while Loop
The do-while loop is an exit control loop which means, it first enters the loop, executes the
statements, and then checks the condition. Therefore, a statement is executed at least once using
the do…while loop. After executing once, the program is executed as long as the condition holds
true.
Syntax
do {
// Code is executed
} while ( condition );
Example: Printing numbers from 1 to 5.
<?php
$num = 1;
do {
echo $num . " ";
$num++;
} while ($num <= 5);
?>
Foreach Loop
The foreach loop in PHP is a specialized construct designed for iterating over arrays and objects.
It simplifies the process of accessing each element without the need for manual index management,
making it a popular choice for developers.
Syntax of the Foreach Loop
The basic syntax for the foreach loop is as follows:
foreach ($array as $value) {
// Code to be executed for each element
}
Syntax with Keys
If you want to access both the keys and values in an associative array, you can use this syntax:
foreach ($array as $key => $value) {
// Code to be executed for each key-value pair
}
Example:
<?php
$numbers = array(10, 20, 30, 40, 50);
foreach ($numbers as $value) {
echo "$value";
}
?>
Using Foreach with Associative Arrays
<?php
$person = array("name" => "John", "age" => 30, "email" => "[email protected]");
foreach ($person as $key => $value) {
echo "$key: $value ";
}
?>
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($numbers as $number) {
if ($number % 2 === 0) {
continue; // Skip even numbers
}
echo "$number <br>";
if ($number === 7) {
break; // Stop when reaching number 7
}
}
?>
Break Statement
The break statement is used to terminate the execution of a loop (such as for, while, do-while,
or foreach) or to exit from a switch statement. When the break statement is encountered, control is
transferred to the first statement following the loop or switch.
Syntax
break; // Exits the current loop or switch
Example:
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i equals 5
}
echo $i . "<br>";
}
?>
Continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next iteration. It
can be used in for, while, do-while, and foreach loops.
Syntax
continue; // Skips to the next iteration of the loop
Example:
<?php
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . "<br>";
}
?>
Functions in PHP
Functions in PHP are reusable blocks of code that can take inputs, process them, and return a
value. They help organize code, make it more readable, and eliminate redundancy by allowing
you to call the same code multiple times with different inputs.
Types of Functions
1. Built-in Functions: These are predefined functions provided by PHP for various tasks,
such as string manipulation, mathematical calculations, and file handling.
2. User-defined Functions: These are functions created by the user to perform specific tasks
tailored to their needs.
Syntax:
function functionName($parameter1, $parameter2, ...) {
// Code to be executed
return $value; // Optional
}
• functionName: The name of the function (must start with a letter or underscore).
• $parameter1, $parameter2: Optional parameters that can be passed to the function.
• return: This keyword is used to return a value from the function (optional).
Example 1:
<?php
function greet() {
echo "Hello, World!";
}
// Calling the function
greet();
?>
Example 2:
<?php
function add($a, $b) {
return $a + $b;
}
// Calling the function with arguments
$result = add(5, 10);
echo "The sum is: " . $result;
?>
Default Parameter Values
<?php
function greetUser($name = "Guest") {
echo "Hello, " . $name . "!";
}
greetUser(); // Uses default value
greetUser("Alice"); // Uses provided value
?>
Returning values in Function
<?php
function getUserInfo() {
$name = "Alice";
$age = 30;
$email = "
[email protected]";
// Return multiple values as an array
return [$name, $age, $email];
}
// Retrieve the returned array
$userInfo = getUserInfo();
list($name, $age, $email) = $userInfo; // Destructure the array into variables
echo "Name: $name, Age: $age, Email: $email"; // Output: Name: Alice, Age: 30, Email:
[email protected]
?>