Introduction to Functions • A function is a block of code that performs a specific task. • Advantages: - Code reusability - Better readability • Types: - Built-in - User-defined
Simple Function • A function without parameters. Example: function simple() { echo 'Welcome to PHP'; } simple();
Parameterized Function • Functions that accept parameters. Example: function add($a, $b) { echo $a + $b; } add(23,34);
Call by Value • Default in PHP. • Original variable not affected. Example: function increment($i){ $i++; } $i=10; increment($i); Output: 10
Call by Reference • Use & symbol. • Original variable is modified. Example: function increment(&$i){ $i++; } $i=10; increment($i); Output: 11
Default Argument Function • Parameters can have default values. Example: function msg($name='Study'){ echo 'Welcome $name'; } msg(); // Welcome Study msg('Glance'); // Welcome Glance
Recursive Function • Function calls itself. • Used in factorial, Fibonacci, etc. Example: function factorial($n){ if($n<=1) return 1; return $n*factorial($n-1); } factorial(5); // 120