← Back to Chapters

PHP Functions

? PHP Functions

⚡ Interactive Logic Tester

Select a function logic to test how PHP processes data:

Result will appear here...

? Functions with Parameters

PHP functions can accept parameters, allowing the function to work with different values and enhancing reusability.

? View Code Example
// Function syntax with parameters
function functionName($param1, $param2) {
    // code to execute
}
? View Code Example
// Greeting function using a parameter
<?php
function greet($name) {
    echo "Hello, $name!";
}
greet("John");
?>

? Functions with Return Value

PHP functions can return a value using the return statement.

? View Code Example
// Function returning a value
function functionName($param1, $param2) {
    return $param1 + $param2;
}
? View Code Example
// Adding two numbers using return
<?php
function add($a, $b) {
    return $a + $b;
}
echo add(3, 4);
?>

? Function Argument By Reference

Arguments passed by reference allow direct modification of original variables.

? View Code Example
// Passing argument by reference
function functionName(&$param) {
    $param++;
}
? View Code Example
// Incrementing a value by reference
<?php
function increment(&$value) {
    $value++;
}
$num = 10;
increment($num);
echo $num;
?>

? PHP Variable Functions

Functions can be called dynamically using variables.

? View Code Example
// Variable function call syntax
function greet() {
    echo "Hello World!";
}
$func = "greet";
$func();

? PHP Recursive Function

Recursive functions call themselves to solve repeated sub-problems.

? View Code Example
// Recursive factorial function
<?php
function factorial($n) {
    if ($n == 0) {
        return 1;
    }
    return $n * factorial($n - 1);
}
echo factorial(5);
?>

? PHP Global & Local Variables

Global variables are accessed using the global keyword.

? View Code Example
// Accessing global variable inside function
<?php
$x = 5;
function test() {
    global $x;
    echo $x;
}
test();
?>

✅ Tips & Best Practices

  • Prefer parameters over global variables.
  • Always define base cases in recursion.
  • Use return values for reusable logic.

? Try It Yourself

  • Create a Fibonacci function using recursion.
  • Write a function to check even or odd.
  • Implement dynamic function calls.
  • Practice passing arguments by reference.