This article explains PHP functions in detail, from basics to advanced topics. It covers built-in functions, user-defined functions, and anonymous functions, including how to use them, setting default values for arguments, specifying return types, and variable scopes (local, global, and superglobal). It also introduces best practices useful for beginners to intermediate PHP developers.
What Are PHP Functions? Explanation of Basic Roles and Features
PHP functions are “named blocks that encapsulate specific processes.” This offers the following advantages.
- Code Reusability
If you want to reuse the same process repeatedly, you can write a function once and call it multiple times. For example, if you put mail sending or calculation processes in functions, you can avoid code duplication. - Improved Code Readability
Splitting a long program into several functions makes the overall structure easier to grasp, simplifying understanding and maintenance. - Easier Debugging
Dividing processing by functions helps you pinpoint which function is causing an issue when a problem occurs.
Additionally, PHP functions are divided into three types: “built-in functions,” “user-defined functions,” and “anonymous (closure) functions.”
1. Built-in Functions
Functions that PHP provides by default.
Examples: strlen()
(to get the length of a string), array_push()
(to add an element to an array), etc.
Features
- Immediately usable as standard PHP features
- Hundreds to thousands of functions are available
- Fast and stable
2. User-Defined Functions
Functions created by developers themselves.
Used for code reuse and summarizing processing.
Example Syntax
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Taro"); // Hello, Taro!
Features
- You can encapsulate arbitrary processing
- Arguments and return values can be freely defined
- Improves readability and maintainability in large codebases
3. Anonymous Functions (Closures)
Functions without a name that are defined inline and can be assigned to variables or used as callback functions.
Example Syntax
$sayHello = function($name) {
return "Hello, " . $name;
};
echo $sayHello("Alice"); // Hello, Alice
Features
- No name means it’s useful for one-time processing or callbacks
- Can capture variable scope as a closure
- Simple and flexible code usage
Summary of the Three Types of Functions
Type | Description | Features |
---|---|---|
Built-in Functions | Functions included standard in PHP | Immediately usable, fast, stable |
User-Defined Functions | Functions created by developers | Ideal for reuse and organizing processing |
Anonymous Functions | Functions without a name | Useful for callbacks and temporary processing, highly flexible |
How to Create PHP Functions (User-Defined Functions): Basic Syntax and Usage
Further explanation on key points when creating functions.
function functionName(argument1, argument2, ...) {
// Write processing here
}
- Function Naming Rules
Function names usually start with lowercase letters, and consist of alphanumeric characters and underscores (_). Case is not distinguished but consistency is recommended.
Example:calculateSum
,get_user_name
- Multiple Arguments Allowed
Arguments can be specified separated by commas. Functions can be created without any arguments. - How to Call
Call a function using the syntaxfunctionName()
. If there are arguments, pass values when calling.
Example of a Simple Function
function sayHello() {
echo "Hello!";
}
sayHello(); // Displays "Hello!"
How to Specify Default Argument Values: Understanding the Use of Default Values
Default values act as a “safety net” when no argument is passed. They are especially useful for optional arguments.
Rules for Specifying Default Values
Arguments with default values must be placed toward the end of the function definition. Arguments without default values must come first.
function profile($name, $age = 20) {
echo "Name: $name, Age: $age";
}
profile("Suzuki"); // Uses default age of 20
profile("Sato", 25); // Uses age of 25
Type of Default Values
Default values must be constants or literals (strings, numbers, etc.). Dynamically computed values or variables cannot be specified.
Introduction and Usage of Commonly Used PHP Built-in Functions
PHP has over 1000 built-in functions, but here are some basic ones beginners often use.
date()
Retrieves and formats date and time.
echo date("Y-m-d"); // e.g., 2025-06-25
strlen()
Gets the length of a string.
echo strlen("Hello"); // 5
strpos($a, $b)
Finds the position of the first occurrence of a character or substring within a string. Returns false if not found.
$pos = strpos("abcdef", "cd");
if ($pos !== false) {
echo "Position is $pos"; // Displays 2 (counting from 0)
} else {
echo "Not found";
}
array_push($arr, $a)
Adds an element to the end of an array.
$arr = [1, 2];
array_push($arr, 3);
print_r($arr); // [1, 2, 3]
array_merge($arr1, $arr2)
Combines two arrays into a new array.
$a = [1, 2];
$b = [3, 4];
$c = array_merge($a, $b);
print_r($c); // [1, 2, 3, 4]
file_get_contents($filename)
Reads the contents of a file as a string.
$content = file_get_contents("sample.txt");
echo $content;
It is recommended to refer to the official documentation to learn how to use these functions.
How to Use Arguments and Return Values: Understanding Function Input and Output
What Are Function Return Values? Mechanism of Return and Assignment to Variables
Functions not only execute processing but also can “return results.” These results are called “return values.”
Using return values, functions can act as “machines that calculate” or “machines that transform data.”
1. return
Signals the End of Function Processing
return
is a command that says “return this value and end the function.”
The value written after return
is returned to the caller.
Also, once return
executes, the function ends there.
That means any code after return
will not run.
function checkNumber($n) {
if ($n < 0) {
return "Negative number"; // Processing ends here, returns string
}
return "Zero or positive number"; // Returned if $n is 0 or more
// Code after this line is not executed
}
echo checkNumber(-1); // Displays "Negative number"
echo checkNumber(5); // Displays "Zero or positive number"
2. Return Values Can Be Assigned to Variables and Used
Return values can be displayed directly or assigned to variables for further processing.
function add($a, $b) {
return $a + $b; // Returns the sum
}
$result = add(3, 7); // Assign return value to $result
echo $result; // Displays 10
3. Return Types Can Be Specified (PHP 7 and Later)
From PHP 7, you can declare the “type” of the return value in advance.
For example, a function that always returns an integer can be written like this:
function addInt(int $a, int $b): int {
return $a + $b; // Returns the result as an integer (int)
}
Specifying the type helps prevent mistakes where the function accidentally returns a value of a different type.
4. Use void
for Functions That Don’t Return Values (PHP 7.1 and Later)
Functions that do not return a value can explicitly declare void
to indicate “no return value.”
function sayHi(): void {
echo "Hi!"; // Just displays a greeting, returns no value
}
void
functions must not use return
with a value.
(Using return;
without a value is allowed, but returning a value is prohibited.)
What Is Variable Scope in PHP? Difference Between Local and Global Variables
Local variables are created inside functions and can only be used within those functions. They disappear once the function finishes.
Global variables are created outside functions and can be used throughout the program. However, to use them inside a function, special designation is required.
1. Local Variables Can Only Be Used Inside Functions
Variables created inside a function are called “local variables.”
These variables can only be used inside that function and are destroyed after the function ends.
function myFunction() {
$localVar = "This is a local variable";
echo $localVar; // Usable here
}
myFunction();
// echo $localVar; // Error here (cannot use outside the function)
In other words, local variables cannot be viewed or modified from outside the function.
2. Global Variables Can Be Used Throughout the Program
Variables created outside functions are called “global variables” and are generally accessible from anywhere in the program.
However, you cannot directly use global variables inside functions.
You need a special method to access global variables inside functions.
3. Use the global
Keyword to Use Global Variables Inside Functions
Inside a function, use the global
keyword to tell PHP “this is a global variable” to use the global variable.
$globalVar = "Global variable";
function useGlobal() {
global $globalVar; // Makes $globalVar usable inside this function
echo $globalVar;
}
useGlobal(); // Displays "Global variable"
If you don’t use global
, the function’s inside is a separate “local world” where global variables are invisible.
4. Another Way: Use the $GLOBALS
Array
PHP has a special array called $GLOBALS
that contains all global variables.
Using this array inside a function allows access to global variables.
$var = "Test";
function test() {
echo $GLOBALS['var']; // Uses global variable $var here
}
test(); // Displays "Test"
You access $GLOBALS
by specifying the variable name as a string key.
What Are Superglobal Variables? Usage and Precautions
PHP provides several special variables called “superglobal variables.”
These are automatically prepared by PHP and accessible anywhere, convenient arrays.
Superglobals are mainly used to handle information sent from the web (HTTP requests) and server environment information.
Main Superglobals, Their Uses, and Example Code
Variable | Use | Example Code |
---|---|---|
$_GET | Retrieve URL query parameters | echo $_GET['id']; ↓ If URL?id=123, displays 123 |
$_POST | Retrieve POST data from forms | echo $_POST['username']; ↓ Displays the username sent from the form |
$_SESSION | Handle user session information | session_start(); $_SESSION['user'] = 'tanaka'; echo $_SESSION['user']; // tanaka |
$_COOKIE | Handle browser cookie information | echo $_COOKIE['site_lang']; ↓ Displays the value of cookie site_lang |
$_SERVER | Get server and runtime environment info | echo $_SERVER['HTTP_USER_AGENT']; ↓ User’s browser info |
Precautions When Using
Since these variables contain data directly from users or external sources, it is essential to handle them safely.
If they contain invalid data, security issues or unexpected behavior can occur.
- Always perform validation (checking correctness) of input values
- Perform sanitization to remove unnecessary characters
For example, when using $_GET['id']
, check if it is numeric and verify it doesn’t contain HTML tags.
if (isset($_GET['id']) && ctype_digit($_GET['id'])) {
$id = (int)$_GET['id'];
echo "ID is {$id}.";
} else {
echo "Invalid ID.";
}
Best Practices and Efficient Usage of PHP Functions
- Write Comments
Write comments explaining the function’s role, argument meanings, and return value types and contents so that others and yourself can easily understand. - Adhere to the DRY Principle
“Don’t Repeat Yourself”: consolidate duplicated code into functions to make maintenance easier. - Test Functions
Small functions are easier to write unit tests for, which helps catch bugs early. - Consider Error Handling
Decide how to handle unexpected input in functions — whether to throw exceptions or return false/null. - Use Namespaces
In large projects, use namespaces to prevent function name conflicts.
namespace MyProject\Utils;
function add($a, $b) {
return $a + $b;
}