PHP Functions
A function in PHP is a reusable block of code that performs a specific task. Functions help organize code, avoid repetition, and make programs easier to maintain. A function can take input data (parameters) and can return a result.
Defining a Function
A function is defined using the function keyword, followed by the function name and parentheses. The code that the function executes is placed between curly braces { ... }.
Simple Example
<?php
// Define a simple function that displays a message
function greet() {
echo "Hello, world!";
}
// Call the function
greet(); // outputs: Hello, world!
?>
Step-by-Step Explanation
function greet()- declares a function named greet.- The code inside the curly braces (
{ ... }) executes only when we call the function. greet();- the function call, which runs the code inside.
Why Use Functions?
Functions allow us to:
- Reuse code without rewriting it.
- Split programs into smaller, easier-to-read modules.
- Organize code logically, which helps with maintenance and debugging.
- Return results that can be used later in the program.
Parameters and Return Values in Functions
Parameters allow functions to receive data from the caller. They are defined inside the function parentheses. A function can also return a result using the return keyword.
Simple Example with Parameters
<?php
// Function that takes a name and greets that person
function greetPerson($name) {
echo "Hello, $name!";
}
// Call the function with different values
greetPerson("Mary"); // Hello, Mary!
greetPerson("John"); // Hello, John!
?>
Example with Return
<?php
// Function that adds two numbers and returns the result
function add($a, $b) {
return $a + $b;
}
$result = add(5, 10);
echo "The result is: $result"; // The result is: 15
?>
Step-by-Step Explanation
- In the first example, the
greetPersonfunction takes a parameter$nameand uses it in the message. - In the second example, the
addfunction takes two parameters, adds them together, and returns the result. This can be stored in a variable or used directly. returnstops the function execution and sends the value back to the caller.
Why Use Parameters and Return
Parameters make functions flexible, so we can use the same function for different data. Returned values allow us to work with results and use them in calculations, conditions, or later output.
Built-in Functions in PHP
PHP provides many built-in functions that help you perform common tasks without writing code from scratch. These functions are grouped into categories: string manipulation, arrays, dates, math, files, and many more.
Useful Examples for Strings
<?php
$text = "Hello, world!";
// Get the length of a string
echo strlen($text); // 13
// Convert text to uppercase
echo strtoupper($text); // HELLO, WORLD!
// Convert text to lowercase
echo strtolower($text); // hello, world!
?>
Useful Examples for Arrays
<?php
$fruits = ["apples", "pears"];
// Add an element to the end of the array
array_push($fruits, "bananas");
print_r($fruits); // Array ( [0] => apples [1] => pears [2] => bananas )
// Remove the last element
$last = array_pop($fruits);
echo $last; // bananas
?>
Examples for Dates and Time
<?php
// Get the current date
echo date("d-m-Y"); // e.g. 01-09-2025
// Get the current time
echo date("H:i:s"); // e.g. 17:45:30
?>
Explanations and Best Practices
- Built-in functions save you from rewriting code and make applications faster.
- It's important to check the documentation for parameters and return values, since some functions may modify data directly or return a value.
- Combining built-in functions with your own custom functions allows you to create powerful and modular applications.
Anonymous Functions and Arrow Functions in PHP
An anonymous function is a function without a name, which can be stored in a variable or passed as a parameter to other functions. Arrow functions are a shorter version introduced in PHP 7.4, more concise and readable, especially useful for short functions.
Example of an Anonymous Function
<?php
$greet = function($name) {
return "Hello, $name!";
};
echo $greet("Mary"); // Hello, Mary!
?>
Example of an Arrow Function
<?php
$sum = fn($a, $b) => $a + $b;
echo $sum(5, 7); // 12
?>
When to Use Anonymous or Arrow Functions
- In callbacks for arrays or built-in functions (e.g.,
array_map,array_filter). - When you want to write short and concise functions without creating global functions.
- Arrow functions are useful when the function returns a single expression and you want clearer code.
Local, Global, and Static Variables in PHP
Local Variables
A variable declared inside a function is local. It exists only in that context and cannot be accessed outside the function.
Example of a Local Variable
<?php
function greet() {
$message = "Hello, world!";
echo $message;
}
greet(); // Displays: Hello, world!
echo $message; // Error: variable is not defined outside the function
?>
Global Variables
A variable defined outside of functions is global. To use it inside a function, we can use the global keyword or the $GLOBALS superglobal.
Example of a Global Variable
<?php
$globalMessage = "Hello from outside the function!";
function showGlobal() {
global $globalMessage;
echo $globalMessage;
}
showGlobal(); // Displays: Hello from outside the function!
?>
Static Variables
A static variable keeps its value between function calls. Unlike regular local variables, it does not reset every time the function is executed.
Example of static variable
<?php
function staticCounter() {
static $callCount = 0;
$callCount++;
echo "The function has been called $callCount times <br>";
}
staticCounter(); // The function has been called 1 time
staticCounter(); // The function has been called 2 times
staticCounter(); // The function has been called 3 times
?>
When to use global and static variables?
- Global: when you need to access a value defined outside the function.
- Static: when you want to preserve the state of a variable between function calls without using a global variable.
Practical example: function to calculate the average grade
We will create a function that takes an array of grades and returns their average. The function will use parameters and return.
Example function for calculating the average grade
<?php
function calculateAverage($grades) {
$sum = array_sum($grades); // sum up all grades
$gradeCount = count($grades); // number of grades
if ($gradeCount === 0) {
return 0; // avoid division by zero
}
return $sum / $gradeCount; // calculate average
}
// Test the function
$studentGrades = [8, 9.5, 7, 10];
$average = calculateAverage($studentGrades);
echo "The student's average is: $average";
?>
<?php
function calculateAverage($grades) {
$sum = array_sum($grades); // sum all grades
$count = count($grades); // number of grades
if ($count === 0) {
return 0; // avoid division by zero
}
return $sum / $count; // calculate average
}
// Test the function
$studentGrades = [8, 9.5, 7, 10];
$average = calculateAverage($studentGrades);
echo "The student's average is: $average";
?>
Step-by-step explanation
- Parameter: $grades - the array of grades passed to the function.
- array_sum: sums all elements of the array.
- count: determines how many elements are in the array.
- We check if the number of grades is 0 to avoid division by zero.
- We return the average and display the result using
echo.
Practical extension
We can modify the function to receive grades from a form and return the average with two decimals:
<?php
$studentGrades = [8, 9.5, 7, 10];
$average = calculateAverage($studentGrades);
echo "The student's average is: " . number_format($average, 2);
?>
