Functions in PHP are reusable blocks of code that perform a specific task. They can simplify your code and enhance its readability and maintainability.

Defining Functions

To define a function in PHP, use the function keyword followed by the function name, parentheses, and a block of code.

  • Basic Function Definition:
  function functionName() {
    // Code to be executed
}
  
  • Calling a Function:
  functionName(); // Executes the function
  

Function Parameters and Return Values

Functions can accept parameters and return values.

  • Function with Parameters:
  function greet($name) {
    return "Hello, " . $name;
}

echo greet("Alice"); // Outputs: Hello, Alice
  
  • Function with Default Parameters:
  function greet($name = "Guest") {
    return "Hello, " . $name;
}

echo greet(); // Outputs: Hello, Guest
  
  • Returning Values:
  function add($a, $b) {
    return $a + $b;
}

$sum = add(5, 3); // $sum is 8
  

Variable Scope

Variable scope determines where a variable can be accessed within your code.

  • Local Scope:

Variables declared inside a function are local to that function and cannot be accessed outside it.

  function myFunction() {
    $localVar = "I am local";
}

// $localVar is not accessible here
  
  • Global Scope:

Variables declared outside functions are global and can be accessed anywhere outside functions.

  $globalVar = "I am global";

function myFunction() {
    global $globalVar;
    echo $globalVar; // Outputs: I am global
}
  
  • Static Variables:

Static variables retain their value between function calls.

  function counter() {
    static $count = 0;
    $count++;
    echo $count;
}

counter(); // Outputs: 1
counter(); // Outputs: 2
  

Built-in Functions

PHP provides many built-in functions for various tasks. You can find a comprehensive list in the PHP Manual.

  • Examples:
    • String Functions:

        echo strlen("Hello"); // Outputs: 5
        
    • Array Functions:

        $array = array(1, 2, 3);
      print_r(array_reverse($array)); // Outputs: Array ( [0] => 3 [1] => 2 [2] => 1 )
        

Anonymous Functions and Lambda Expressions

Anonymous functions, also known as closures or lambda expressions, are functions without a name.

  • Defining an Anonymous Function:
  $greet = function($name) {
    return "Hello, " . $name;
};

echo $greet("Bob"); // Outputs: Hello, Bob
  
  • Using Anonymous Functions in Arrays:
  $numbers = array(1, 2, 3, 4);
$squared = array_map(function($number) {
    return $number * $number;
}, $numbers);

print_r($squared); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
  

Functions in PHP are fundamental for creating modular, maintainable, and reusable code, and understanding how to use them effectively can greatly enhance your development workflow.