Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

2. Advanced Functions & Error Handling

Lesson 16 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

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

FeaturePass by ValuePass by Reference
SymbolNothing (default)& before parameter
What is passed?A copy of the valueThe memory address
Original variable changed?NoYes
SafetySafer (original protected)Riskier (original can be modified)
When to useMost function callsWhen 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:

  1. Base Case: The condition that terminates the recursion.
  2. 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:

FunctionPurposeExample Output
strlen($str)Returns length of stringstrlen("Hello") → 5
strtoupper($str)Convert to uppercasestrtoupper("hello") → "HELLO"
strtolower($str)Convert to lowercasestrtolower("WORLD") → "world"
str_replace($f, $r, $s)Replace substringstr_replace("PHP","Java","I love PHP") → "I love Java"
strpos($str, $find)Find position of substringstrpos("Hello","ll") → 2
trim($str)Remove whitespace from start/endtrim(" Hello ") → "Hello"
substr($str, $start, $len)Extract a portion of a stringsubstr("Hello",1,3) → "ell"
str_word_count($str)Count wordsstr_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 TypeSeverityEffect on ExecutionCommon CauseExample
NoticeLowScript continuesUndefined variable, missing array indexecho $undefinedVar;
WarningMediumScript continuesMissing file, wrong argumentinclude 'missing.php';
Fatal ErrorCriticalScript STOPSCalling undefined function, wrong typescallUndefinedFunction();
Parse ErrorCriticalScript STOPSSyntax mistakeecho "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

  1. Detection: PHP engine identifies a syntax, runtime, or logic issue.
  2. Reporting: Based on error_reporting settings, the error is flagged.
  3. Handling: Custom handlers or default engine actions take over.
  4. Logging: Errors are recorded to server logs for debugging without exposing them to users.

Best Practices for Exams:

TipExplanation
Always Use die()When opening files or DB connections, append or die("msg") for immediate safety.
Check return valuesFunctions like mail() return bool; always check this before confirming success to the user.
Environment CheckUse @ (error suppression operator) sparingly, only when you manually handle the outcome immediately after.
Recursion LimitBe aware that deep recursion can lead to "Stack Overflow"; always ensure a strong base case.