Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

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

Why Use Functions?

Functions allow us to:

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

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

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

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?

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";
?>
🔧 Exemplu PHP: funcție pentru calcularea mediei notelor
<?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

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

🧠 Quiz - Functions in PHP

Top