Contents

PHP Functions

PHP Functions

A function is a set of instructions packaged into a single block that performs a specific task. To better understand how functions work, consider this analogy: imagine a boss asking an employee to compute the annual budget. The employee collects relevant data, performs the necessary calculations, and provides the result to the boss. Similarly, functions in programming take input (called parameters), perform operations, and return results.

PHP provides two types of functions:
  • Built-in Functions: PHP has a large collection of pre-defined functions such as strlen(), array_push(), fopen(), etc., which we can call directly.
  • User-Defined Functions: In addition to built-in functions, PHP also allows us to create custom functions to encapsulate reusable code blocks.
Why Use Functions?
  • Reusability: Functions allow you to reuse code across multiple parts of your program, minimizing redundancy.
  • Easier Error Detection: Since the code is divided into functions, it becomes easier to detect errors in specific parts.
  • Easy Maintenance: Functions make it easier to modify code, as changes within a function automatically propagate wherever the function is used.
Why Use Functions?
  • Reusability: Functions allow you to reuse code across multiple parts of your program, minimizing redundancy.
  • Easier Error Detection: Since the code is divided into functions, it becomes easier to detect errors in specific parts.
  • Easy Maintenance: Functions make it easier to modify code, as changes within a function automatically propagate wherever the function is used.
				
					function functionName() {
    // Code to be executed
}

				
			

Example

				
					<?php

function greet() {
    echo "Welcome to PHP!";
}

// Calling the function
greet();

?>

				
			

Output:

				
					Welcome to PHP!

				
			
Function Parameters (Arguments)

Parameters allow a function to accept input values during its execution. These parameters are specified inside the parentheses of the function. The values passed to these parameters during function calls are known as arguments.

Syntax:

				
					function functionName($param1, $param2) {
    // Code to be executed
}

				
			

Example:

				
					<?php

function add($a, $b) {
    $sum = $a + $b;
    echo "The sum is $sum";
}

// Calling the function with arguments
add(5, 10);

?>

				
			

Output:

				
					The sum is 15

				
			
Setting Default Parameter Values

PHP allows setting default values for parameters. If an argument isn’t passed during the function call, the default value is used.

Example:

				
					<?php

function introduce($name, $age = 30) {
    echo "$name is $age years old.\n";
}

// Function calls
introduce("John", 25);  // Passes both parameters
introduce("Jane");      // Uses default age

?>

				
			

Output:

				
					John is 25 years old.
Jane is 30 years old.

				
			
Returning Values from Functions

A function can also return a value using the return keyword. The returned value can be of any type, such as strings, numbers, arrays, or objects.

Example:

				
					<?php

function multiply($a, $b) {
    return $a * $b;
}

// Storing the returned value
$result = multiply(4, 5);
echo "The product is $result";

?>

				
			

Output:

				
					The product is 20

				
			
Passing Parameters by Value and Reference

PHP allows you to pass function arguments either by value or by reference:

  • Pass by Value: A copy of the original value is passed to the function. Changes made inside the function don’t affect the original value.
  • Pass by Reference: The actual memory reference of the variable is passed, so changes made inside the function affect the original variable.

Example:

				
					<?php

// Pass by value
function incrementByValue($num) {
    $num += 5;
    return $num;
}

// Pass by reference
function incrementByReference(&$num) {
    $num += 10;
    return $num;
}

$number = 20;

incrementByValue($number);
echo "After pass by value: $number\n";  // Original value unchanged

incrementByReference($number);
echo "After pass by reference: $number\n";  // Original value changed

?>

				
			

Output:

				
					After pass by value: 20
After pass by reference: 30

				
			

PHP Arrow Functions

Arrow functions, introduced in PHP 7.4, provide a compact syntax for defining anonymous functions. They offer a more concise way to write single-line functions, which makes the code more readable and easier to manage.

Syntax:

				
					$fn = fn($x) => expression;

				
			

Example 1: Calculating the Product of Array Elements Using Arrow Functions

In this example, we’ll declare an array and use the array_reduce() function combined with an arrow function to calculate the product of all the elements in the array.

				
					<?php

// Declare an array
$numbers = [2, 3, 4];

// Using array_reduce with an arrow function to find the product
$product = array_reduce($numbers, fn($carry, $item) => $carry * $item, 1);

echo $product;

?>

				
			

Output:

				
					24

				
			

Example 2: Squaring Each Element of an Array Using Arrow Functions

In this example, we’ll declare an array and use the array_map() function to square each element in the array using an arrow function.

				
					<?php

// Declare an array
$values = [2, 3, 4, 5];

// Using array_map with an arrow function to square each element
$squares = array_map(fn($n) => $n ** 2, $values);

print_r($squares);

?>

				
			

Output:

				
					Array
(
    [0] => 4
    [1] => 9
    [2] => 16
    [3] => 25
)

				
			

Anonymous recursive function in PHP

Anonymous recursive functions are a type of recursion where a function doesn’t explicitly call another function by name. Instead, recursion is achieved through the function referring to itself implicitly, often via closures or higher-order functions. These functions enable recursion without requiring a named function, which is particularly useful in scenarios where anonymous functions (closures) are used.

Use of Anonymous Recursion:
  • Anonymous recursion is primarily used for recursion in anonymous functions, especially in closures or as callbacks.
  • It avoids the need to bind the function’s name explicitly, making the code more flexible in certain contexts.
Alternatives:
  • Named functions can be used for recursion, but with anonymous functions, recursion can still be implemented by referring to the function within itself using mechanisms like closures.

Example 1: Countdown with Anonymous Recursive Function

The following example demonstrates anonymous recursion in PHP, where a function counts down from a specific number to 1.

				
					<?php  
// PHP program demonstrating anonymous recursion

$countdown = function ($limit = null) use (&$countdown) {  
    static $current = 5;  
    
    // If $current reaches 0, stop recursion.
    if ($current <= 0) {  
        return false; 
    }  
    
    // Print the current value
    echo "$current\n";  
    
    // Decrement the value of $current
    $current--;  
    
    // Recursive call
    $countdown();  
};  

// Function call
$countdown();
?> 

				
			

Output:

				
					5
4
3
2
1

				
			

Example 2: Calculating Factorial with Anonymous Recursive Function

The next example calculates the factorial of a given number using anonymous recursion.

				
					<?php 
// PHP program demonstrating anonymous recursive function

$factorial = function($num) use (&$factorial) { 
    
    // Base case for recursion
    if ($num == 1)  
        return 1; 

    // Recursive case: multiply the current number by factorial of (num - 1)
    return $num * $factorial($num - 1); 
}; 

// Function call to compute the factorial of 4
echo $factorial(4); 
?> 

				
			

Output:

				
					24