PHP Functions

PHP functions are blocks of reusable code that perform specific tasks. Functions in PHP can be built-in (like strlen(), array_merge(), etc.) or user-defined.

Syntax for a User-Defined Function

function functionName($parameter1, $parameter2) { // Code to be executed return $result; }

Example

function addNumbers($a, $b) { return $a + $b; } echo addNumbers(5, 10); // Output: 15

Common Built-In PHP Functions

Category Function Examples
String strlen(), str_replace(), strpos(), substr()
Array array_push(), array_merge(), in_array()
Math abs(), round(), rand(), max()
Date/Time date(), time(), strtotime()
File Handling fopen(), fwrite(), fread(), fclose()
Variable isset(), empty(), unset()

Functions with Default Parameters

function greet($name = "Guest") { return "Hello, $name!"; } echo greet(); // Hello, Guest! echo greet("Alice"); // Hello, Alice!

Anonymous Functions (Closures)

$square = function($n) { return $n * $n; }; echo $square(4); // Output: 16