PHP Functions
What are Functions?
Section titled “What are Functions?”- Functions are reusable blocks of code that perform specific tasks.
- They help organize code, reduce repetition, and make programs more modular and maintainable.
- PHP provides both built-in functions and the ability to create custom user-defined functions.
Function Basics
Section titled “Function Basics”Declaring Functions
Section titled “Declaring Functions”Functions in PHP are declared using the function keyword:
<?phpfunction functionName($parameter1, $parameter2 = 'default'): returnType {    // Function body    return $value;}<?php// Union types allow multiple parameter typesfunction calculateArea(int|float $width, int|float $height = 1.0): int|float {    return $width * $height;}
// Trailing commas improve code formattingfunction processUserData(    string $name,    int $age,    bool $active,  // Trailing comma allowed in PHP 8.0+) {    return ['name' => $name, 'age' => $age, 'active' => $active];}<?php// Basic function declarationfunction greet() {    echo "Hello, World!";}
// Call the functiongreet(); // Outputs: Hello, World!?>Function Naming Rules
Section titled “Function Naming Rules”<?php// Valid function namesfunction sayHello() { }function say_hello() { }function sayHello2() { }function _privateFunction() { }
// Invalid function names (these will cause errors)// function 2sayHello() { }  // Cannot start with number// function say-hello() { }  // Cannot contain hyphens// function function() { }   // Cannot use reserved words?>Function Parameters
Section titled “Function Parameters”Functions can accept parameters to make them more flexible:
<?php// Function with single parameterfunction greetUser($name) {    echo "Hello, $name!";}
greetUser("John"); // Outputs: Hello, John!
// Function with multiple parametersfunction addNumbers($a, $b) {    return $a + $b;}
$result = addNumbers(5, 3);echo $result; // Outputs: 8?>Default Parameters
Section titled “Default Parameters”You can provide default values for parameters:
<?phpfunction greetUser($name = "Guest", $greeting = "Hello") {    echo "$greeting, $name!";}
greetUser();                    // Outputs: Hello, Guest!greetUser("John");              // Outputs: Hello, John!greetUser("John", "Hi");        // Outputs: Hi, John!?>Return Values
Section titled “Return Values”Basic Return Statements
Section titled “Basic Return Statements”<?php// Function that returns a valuefunction multiply($a, $b) {    return $a * $b;}
$result = multiply(4, 5);echo $result; // Outputs: 20
// Function that returns different typesfunction getRandomValue() {    $random = rand(1, 3);
    if ($random === 1) {        return "string";    } elseif ($random === 2) {        return 42;    } else {        return true;    }}
$value = getRandomValue();var_dump($value); // Could output: string(6) "string", int(42), or bool(true)?>Returning Arrays and Objects
Section titled “Returning Arrays and Objects”<?php// Returning an arrayfunction getUserData($id) {    return [        'id' => $id,        'name' => 'John Doe',        'email' => 'john@example.com'    ];}
$user = getUserData(1);print_r($user);
// Returning an objectfunction createUser($name, $email) {    $user = new stdClass();    $user->name = $name;    $user->email = $email;    return $user;}
$user = createUser('Jane', 'jane@example.com');echo $user->name; // Outputs: Jane?>Early Returns
Section titled “Early Returns”<?phpfunction validateAge($age) {    if ($age < 0) {        return "Age cannot be negative";    }
    if ($age > 150) {        return "Age seems unrealistic";    }
    return "Valid age";}
echo validateAge(-5);  // Outputs: Age cannot be negativeecho validateAge(25);  // Outputs: Valid age?>Variable Scope
Section titled “Variable Scope”Global vs Local Scope
Section titled “Global vs Local Scope”<?php$globalVar = "I'm global";
function testScope() {    $localVar = "I'm local";    echo $localVar;  // Works fine    // echo $globalVar; // This would cause an error}
testScope(); // Outputs: I'm localecho $globalVar; // Outputs: I'm global// echo $localVar; // This would cause an error?>Using Global Variables
Section titled “Using Global Variables”The global keyword allows functions to access variables defined outside their scope. Without it, functions cannot see or modify global variables.
Why we need global:
- Functions have their own local scope: they can’t access variables from outside by default,
- The globalkeyword creates a reference to the global variable inside the function,
- This allows the function to read and modify the global variable.
<?php$counter = 0;
function incrementCounter() {    global $counter;    $counter++;}
function getCounter() {    global $counter;    return $counter;}
incrementCounter();incrementCounter();echo getCounter(); // Outputs: 2?>Static Variables
Section titled “Static Variables”<?phpfunction countCalls() {    static $count = 0;    $count++;    echo "Function called $count times\n";}
countCalls(); // Function called 1 timescountCalls(); // Function called 2 timescountCalls(); // Function called 3 times?>Function Arguments
Section titled “Function Arguments”Pass by Reference
Section titled “Pass by Reference”Pass by reference allows a function to modify the original variable instead of working with a copy. When you pass a variable by reference using the & symbol, the function receives direct access to the original variable’s memory location.
Key Differences:
- Pass by value (default) - Function gets a copy of the variable
- Pass by reference - Function gets direct access to the original variable
This is useful when you need to:
- Modify the original variable inside the function
- Avoid copying large data structures (performance)
- Return multiple values from a function
<?php// Pass by reference with &function increment(&$number) {    $number++;}
$value = 5;increment($value);echo $value; // Outputs: 6
// Swap function examplefunction swap(&$a, &$b) {    $temp = $a;    $a = $b;    $b = $temp;}
$x = 10;$y = 20;swap($x, $y);echo "$x, $y"; // Outputs: 20, 10?>Variable-Length Argument Lists
Section titled “Variable-Length Argument Lists”<?php// Using func_get_args()function sum() {    $args = func_get_args();    $total = 0;    foreach ($args as $arg) {        $total += $arg;    }    return $total;}
echo sum(1, 2, 3, 4, 5); // Outputs: 15
// Using ... (splat operator) - PHP 5.6+function sumNumbers(...$numbers) {    return array_sum($numbers);}
echo sumNumbers(1, 2, 3, 4, 5); // Outputs: 15
// Mixed parameters with variadicfunction processData($required, ...$optional) {    echo "Required: $required\n";    echo "Optional count: " . count($optional) . "\n";    print_r($optional);}
processData("main", "opt1", "opt2", "opt3");?>Named Arguments (PHP 8.0+)
Section titled “Named Arguments (PHP 8.0+)”<?phpfunction createUser($name, $email, $age = null, $active = true) {    return [        'name' => $name,        'email' => $email,        'age' => $age,        'active' => $active    ];}
// Using named arguments$user = createUser(    name: "John Doe",    email: "john@example.com",    active: false);
// Mixed positional and named arguments$user2 = createUser("Jane", email: "jane@example.com", age: 30);
print_r($user);print_r($user2);?>Built-in Functions
Section titled “Built-in Functions”String Functions
Section titled “String Functions”<?php$text = "Hello World";
// String manipulationecho strlen($text);           // 11echo strtoupper($text);       // HELLO WORLDecho substr($text, 0, 5);     // Helloecho str_replace("World", "PHP", $text); // Hello PHP
// String validationecho is_string($text) ? "Yes" : "No";    // Yesecho ctype_alpha("Hello") ? "Yes" : "No"; // Yes?>Array Functions
Section titled “Array Functions”<?php$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// Array manipulationecho count($numbers);               // 8echo max($numbers);                 // 9echo min($numbers);                 // 1echo array_sum($numbers);           // 31
sort($numbers);print_r($numbers);                  // Sorted array
// Array searchingecho in_array(5, $numbers) ? "Found" : "Not found"; // Foundecho array_search(4, $numbers);    // Returns key/index
// Array transformation$doubled = array_map(function($n) { return $n * 2; }, $numbers);$filtered = array_filter($numbers, function($n) { return $n > 3; });
print_r($doubled);print_r($filtered);?>Math Functions
Section titled “Math Functions”<?php// Basic mathecho abs(-10);              // 10echo round(3.7);            // 4echo ceil(3.2);             // 4echo floor(3.8);            // 3echo pow(2, 3);             // 8echo sqrt(16);              // 4
// Random numbersecho rand(1, 10);           // Random number between 1-10echo mt_rand(1, 100);       // Better random number generator
// Trigonometryecho sin(pi()/2);           // 1echo cos(0);                // 1echo tan(pi()/4);           // 1?>Date and Time Functions
Section titled “Date and Time Functions”<?php// Current timestampecho time();                        // Current Unix timestampecho date('Y-m-d H:i:s');          // Current date/time formatted
// Creating dates$timestamp = mktime(12, 30, 0, 6, 15, 2023);echo date('Y-m-d H:i:s', $timestamp);
// Date parsing$date = strtotime('2023-06-15 12:30:00');echo date('l, F j, Y', $date);     // Thursday, June 15, 2023
// Date arithmeticecho date('Y-m-d', strtotime('+1 week'));echo date('Y-m-d', strtotime('-30 days'));?>