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%

11. Functions in PHP

Lesson 8 of 29 in the free PHP Programming notes on Siksha Sarovar, written by Rohit Jangra.

Functions in PHP

A function is a block of code that performs a specific task and can be reused.

Creating Functions

Syntax

function functionName(){
   // code
}

Example

function greet(){
   echo "Welcome to PHP";
}
greet();
Exam Line: Functions increase code reusability and readability.

---

Passing Arguments to Functions

1. Pass by Value

  • Changes do NOT affect original variable
function add($x){
   $x += 5;
}
$a = 10;
add($a);
echo $a;   // Output: 10

2. Pass by Reference

  • Changes affect original variable
  • Use & symbol
function add(&$x){
   $x += 5;
}
$a = 10;
add($a);
echo $a;   // Output: 15

Difference Table

FeaturePass by ValuePass by Reference
SymbolNone&
Original ValueNot ChangedChanged
Memory UsageMoreLess
Exam Tip: Reference passing is memory efficient.

---

Recursive Functions

A recursive function is a function that calls itself until a condition is met.

Example: Factorial

function factorial($n){
   if($n == 1){
      return 1;
   }
   return $n * factorial($n - 1);
}

echo factorial(5);

Output: 120

Important Rules

  • Must have a base condition
  • Otherwise infinite recursion occurs
Exam Line: Recursive functions require a base condition.

---

Advantages of Functions

  • Code reusability
  • Easy debugging
  • Modular programming
  • Reduced redundancy