Advanced PHP Functions: Arguments, Recursion, Built-ins & Errors
1. Passing Arguments: By Value vs By Reference
When you call a function with arguments, PHP can pass the data in two fundamentally different ways:
a) Pass by Value (Default) Definition: A copy of the variable's value is passed to the function. Any changes made inside the function do NOT affect the original variable in the calling scope.
function addFive($num) {
$num += 5; // Only modifies the local copy
}
$val = 10;
addFive($val);
echo $val; // Output: 10 (original is UNCHANGED)
b) Pass by Reference Definition: The memory address (reference) of the variable is passed. Changes inside the function DO affect the original variable. Use the & symbol before the parameter.
function addFive(&$num) { // & means "pass by reference"
$num += 5;
}
$val = 10;
addFive($val);
echo $val; // Output: 15 (original IS changed)
Comparison Table: By Value vs By Reference
| Feature | Pass by Value | Pass by Reference |
|---|---|---|
| Symbol | Nothing (default) | & before parameter |
| What is passed? | A copy of the value | The memory address |
| Original variable changed? | No | Yes |
| Safety | Safer (original protected) | Riskier (original can be modified) |
| When to use | Most function calls | When you need to modify the caller's variable |
2. Recursion
Definition: Recursion is a technique where a function calls itself to solve a problem. Every recursive function must have a Base Case — a condition that stops the recursion — to prevent an infinite loop.
Structure of a Recursive Function:
- Base Case: The condition that terminates the recursion.
- Recursive Case: The function calls itself with a modified argument, moving closer to the base case.
Example 1: Factorial of a Number
function factorial($n) {
if ($n <= 1) return 1; // Base case: 1! = 1 and 0! = 1
return $n * factorial($n - 1); // Recursive call
}
echo factorial(5); // Output: 120 (5 * 4 * 3 * 2 * 1)
Trace: factorial(5) → 5 factorial(4) → 5 4 factorial(3) → ... → 54321 = 120*
Example 2: Fibonacci Series
function fibonacci($n) {
if ($n <= 1) return $n;
return fibonacci($n - 1) + fibonacci($n - 2);
}
echo fibonacci(7); // Output: 13
3. Important Built-in String Functions
PHP has 1000+ built-in functions. The most commonly used ones for strings:
| Function | Purpose | Example Output |
|---|---|---|
strlen($str) | Returns length of string | strlen("Hello") → 5 |
strtoupper($str) | Convert to uppercase | strtoupper("hello") → "HELLO" |
strtolower($str) | Convert to lowercase | strtolower("WORLD") → "world" |
str_replace($f, $r, $s) | Replace substring | str_replace("PHP","Java","I love PHP") → "I love Java" |
strpos($str, $find) | Find position of substring | strpos("Hello","ll") → 2 |
trim($str) | Remove whitespace from start/end | trim(" Hello ") → "Hello" |
substr($str, $start, $len) | Extract a portion of a string | substr("Hello",1,3) → "ell" |
str_word_count($str) | Count words | str_word_count("Hello World") → 2 |
4. The mail() Function
Used to send an email directly from a PHP script. Requires a correctly configured mail server (e.g., Sendmail/SMTP on the server).
Syntax: mail(to, subject, message, [headers], [parameters])
$to = "student@example.com";
$subject = "Your Exam Result";
$message = "Dear Student, You have passed your exam. Congratulations!";
$headers = "From: admin@college.edu";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Email sending failed.";
}
5. PHP Errors: Types, Causes & Effects
An error is an issue encountered during script execution. PHP has four main error types:
| Error Type | Severity | Effect on Execution | Common Cause | Example |
|---|---|---|---|---|
| Notice | Low | Script continues | Undefined variable, missing array index | echo $undefinedVar; |
| Warning | Medium | Script continues | Missing file, wrong argument | include 'missing.php'; |
| Fatal Error | Critical | Script STOPS | Calling undefined function, wrong types | callUndefinedFunction(); |
| Parse Error | Critical | Script STOPS | Syntax mistake | echo "Hello" (no semicolon) |
Error Handling with die() and trigger_error():
// die() stops execution and prints a message
$conn = mysqli_connect("localhost", "root", "") or die("Connection Failed!");
// Custom error with trigger_error
if ($age < 0) {
trigger_error("Age cannot be negative!", E_USER_WARNING);
}
Custom Error Handler:
function myErrorHandler($errno, $errstr) {
echo "Error [$errno]: $errstr";
}
set_error_handler("myErrorHandler");
Study Deep: Professional Error Management
For University exams and professional PHP development, understanding how to manage errors in a live environment is a key differentiator.
The PHP Error Cycle
- Detection: PHP engine identifies a syntax, runtime, or logic issue.
- Reporting: Based on
error_reportingsettings, the error is flagged. - Handling: Custom handlers or default engine actions take over.
- Logging: Errors are recorded to server logs for debugging without exposing them to users.
Best Practices for Exams:
| Tip | Explanation |
|---|---|
| Always Use die() | When opening files or DB connections, append or die("msg") for immediate safety. |
| Check return values | Functions like mail() return bool; always check this before confirming success to the user. |
| Environment Check | Use @ (error suppression operator) sparingly, only when you manually handle the outcome immediately after. |
| Recursion Limit | Be aware that deep recursion can lead to "Stack Overflow"; always ensure a strong base case. |