Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Functions

Functions are reusable blocks of code that perform a specific task. PHP supports named functions, anonymous functions, arrow functions, and more.

Declaring and Calling Functions

Use the function keyword. Parameters can have default values and type declarations.

Function Basics
<?php
// Basic function
function greet(string $name): string {
    return "Hello, $name!";
}
echo greet("Alice"); // Hello, Alice!

// Default parameter
function power(int $base, int $exp = 2): int {
    return $base ** $exp;
}
echo power(3);    // 9
echo power(3, 3); // 27

// Pass by reference
function addTen(int &$num): void {
    $num += 10;
}
$val = 5;
addTen($val);
echo $val; // 15

// Variadic function
function sum(int ...$nums): int {
    return array_sum($nums);
}
echo sum(1, 2, 3, 4, 5); // 15
?>

Anonymous Functions & Closures

Anonymous functions (closures) have no name and can be assigned to variables or passed as arguments. Use use to capture variables from the outer scope.

Anonymous Functions
<?php
// Anonymous function assigned to variable
$double = function(int $n): int {
    return $n * 2;
};
echo $double(5); // 10

// Closure capturing outer variable
$multiplier = 3;
$multiply = function(int $n) use ($multiplier): int {
    return $n * $multiplier;
};
echo $multiply(4); // 12

// Passing anonymous function as argument
$numbers = [3, 1, 4, 1, 5, 9];
usort($numbers, function($a, $b) { return $a - $b; });
print_r($numbers); // [1, 1, 3, 4, 5, 9]

// array_map with anonymous function
$squared = array_map(fn($n) => $n ** 2, [1, 2, 3, 4]);
print_r($squared); // [1, 4, 9, 16]
?>

Arrow Functions (PHP 7.4+)

Arrow functions use the fn keyword and automatically capture variables from the outer scope without needing use.

Arrow Functions
<?php
$tax = 0.2;

// Arrow function auto-captures $tax
$withTax = fn(float $price): float => $price * (1 + $tax);

echo $withTax(100); // 120

// Chaining with array functions
$prices = [10, 20, 30, 40];
$discounted = array_map(fn($p) => $p * 0.9, $prices);
$expensive  = array_filter($discounted, fn($p) => $p > 20);

print_r($expensive); // [27, 36]
?>

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.