Skip to content

PHP 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.

Functions in PHP are declared using the function keyword:

Syntax for declaring a function:
<?php
function functionName($parameter1, $parameter2 = 'default'): returnType {
// Function body
return $value;
}
<?php
// Union types allow multiple parameter types
function calculateArea(int|float $width, int|float $height = 1.0): int|float {
return $width * $height;
}
// Trailing commas improve code formatting
function processUserData(
string $name,
int $age,
bool $active, // Trailing comma allowed in PHP 8.0+
) {
return ['name' => $name, 'age' => $age, 'active' => $active];
}
Basic function declaration and call:
<?php
// Basic function declaration
function greet() {
echo "Hello, World!";
}
// Call the function
greet(); // Outputs: Hello, World!
?>

<?php
// Valid function names
function 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
?>

Functions can accept parameters to make them more flexible:

<?php
// Function with single parameter
function greetUser($name) {
echo "Hello, $name!";
}
greetUser("John"); // Outputs: Hello, John!
// Function with multiple parameters
function addNumbers($a, $b) {
return $a + $b;
}
$result = addNumbers(5, 3);
echo $result; // Outputs: 8
?>

You can provide default values for parameters:

<?php
function greetUser($name = "Guest", $greeting = "Hello") {
echo "$greeting, $name!";
}
greetUser(); // Outputs: Hello, Guest!
greetUser("John"); // Outputs: Hello, John!
greetUser("John", "Hi"); // Outputs: Hi, John!
?>

<?php
// Function that returns a value
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(4, 5);
echo $result; // Outputs: 20
// Function that returns different types
function 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)
?>

<?php
// Returning an array
function getUserData($id) {
return [
'id' => $id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
}
$user = getUserData(1);
print_r($user);
// Returning an object
function 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
?>

<?php
function 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 negative
echo validateAge(25); // Outputs: Valid age
?>

<?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 local
echo $globalVar; // Outputs: I'm global
// echo $localVar; // This would cause an error
?>

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 global keyword 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
?>

<?php
function countCalls() {
static $count = 0;
$count++;
echo "Function called $count times\n";
}
countCalls(); // Function called 1 times
countCalls(); // Function called 2 times
countCalls(); // Function called 3 times
?>

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 example
function swap(&$a, &$b) {
$temp = $a;
$a = $b;
$b = $temp;
}
$x = 10;
$y = 20;
swap($x, $y);
echo "$x, $y"; // Outputs: 20, 10
?>

<?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 variadic
function processData($required, ...$optional) {
echo "Required: $required\n";
echo "Optional count: " . count($optional) . "\n";
print_r($optional);
}
processData("main", "opt1", "opt2", "opt3");
?>

<?php
function 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);
?>

<?php
$text = "Hello World";
// String manipulation
echo strlen($text); // 11
echo strtoupper($text); // HELLO WORLD
echo substr($text, 0, 5); // Hello
echo str_replace("World", "PHP", $text); // Hello PHP
// String validation
echo is_string($text) ? "Yes" : "No"; // Yes
echo ctype_alpha("Hello") ? "Yes" : "No"; // Yes
?>

<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// Array manipulation
echo count($numbers); // 8
echo max($numbers); // 9
echo min($numbers); // 1
echo array_sum($numbers); // 31
sort($numbers);
print_r($numbers); // Sorted array
// Array searching
echo in_array(5, $numbers) ? "Found" : "Not found"; // Found
echo 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);
?>

<?php
// Basic math
echo abs(-10); // 10
echo round(3.7); // 4
echo ceil(3.2); // 4
echo floor(3.8); // 3
echo pow(2, 3); // 8
echo sqrt(16); // 4
// Random numbers
echo rand(1, 10); // Random number between 1-10
echo mt_rand(1, 100); // Better random number generator
// Trigonometry
echo sin(pi()/2); // 1
echo cos(0); // 1
echo tan(pi()/4); // 1
?>

<?php
// Current timestamp
echo time(); // Current Unix timestamp
echo 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 arithmetic
echo date('Y-m-d', strtotime('+1 week'));
echo date('Y-m-d', strtotime('-30 days'));
?>