PHP Functions

PHP Functions

When you want the machine to perform a task, you define or call a function. A function is a block of code that performs a specific task. You can even define your own functions where you write code from scratch and decide how the function will behave. In this article, we will learn how to define a function in PHP and what functions are specific to PHP, like anonymous functions and arrow functions. In the end, we will take a few examples to understand how functions make it easier for developers.

Table of Contents: 

What is a Function?

A function is a block of code designed to perform a specific task. Once defined, it can be called again and again to perform the same task. This saves time, removes redundancy in code and makes your program modular and easy to understand. For example, you are developing a program for a robot to make tea. In this program, you can have separate functions for preparing heat(), placing a utensil on heat(), adding water(), adding tea leaves(), adding milk(), adding sugar(), boiling(), preparing cups() and finally straining the tea in the cups(). 

Function is PHP

How to Create a Function in PHP?

Functions in PHP are declared using the function keyword. This keyword indicates to the PHP interpreter that the subsequent code block inside the curly braces {} is a function and should be treated like that.

Syntax: 

function functionName($param1, $param2) {  
// Code to be executed 
return $result;
}
  • The function keyword and function name are required. The function name must follow naming conventions, such as not starting with a digit. 
  • Parameters and the return statement are optional. It can be added or removed according to the requirements of the function. 

Parameters and Arguments of Functions in PHP

Parameters and arguments are input values that the functions accept. Parameters are used at the time of function definition and arguments at function calling. 

  • Parameters: They are defined at the function declaration. These are added inside the round brackets () of the function.
  • Arguments: They are the actual values that the user gives in the function. The parameters are assigned these values based on their position. 

In summary, parameters are defined in the function declaration to accept values, and arguments are passed at the function call, which are the actual values. Once the user defines the parameters for a function, then giving no arguments to a function call will lead to an error.

They are passed in two ways: pass by value and pass by reference.

1. Pass by Value

When the arguments are passed by value, the function creates a copy of the values and then works on it. This means the original value does not get modified.

Code:

<?php
function modifyNumber($num) {
    $num = $num + 10;
    echo "Inside function: $numn";
}
$myNumber = 5;
modifyNumber($myNumber);
echo "Outside function: $myNumbern";
?>

Output:

Output - Pass by Value

Explanation: The modifyNumber function receives a copy of $myNumber. Changes made to $num inside the function do not affect the original $myNumber outside, demonstrating pass-by-value behavior.

2. Pass by Reference

When the arguments are passed by reference, the reference value of the original value is given. This means that any modification done inside the function will reflect on the original value. 

Code:

<?php
function appendToList(&$myList) {
    $myList[] = 4;
    echo "Inside function: " . implode(", ", $myList) . "n";
}
$originalList = [1, 2, 3];
appendToList($originalList);
echo "Outside function: " . implode(", ", $originalList) . "n";
?>

Output:

Output - Pass by Reference

Explanation: The appendToList function receives a reference to $originalList (due to &). Modifications like appending an element inside the function directly alter the original array outside.

How to Call a Function in PHP?

Calling a function in PHP is simple. All you have to do is write the function name and add round brackets () after it. If the function you are calling has parameters, then you have to give the arguments as well when calling the function. This is also known as invoking. 

Syntax:

FunctionName()
Or
FunctionName($param1, $param2)

Returning Values in Functions in PHP

Functions in PHP allow you to have a return value of a function, which you can then assign to a variable. You do this using the return statement. If no return statement is provided, it returns null by default. The return value can be of any data type, such as string, list, integer, etc. PHP 7.1 introduced void return type declarations as well.

Syntax: 

When the function returns something

return [expression];

When the function is to be simply exited. 

return;

This returns null and exits the function.

Code:

<?php
function calculateArea($length, $width) {
    return $length * $width;
}
$area = calculateArea(5, 10); 
echo $area;
?>

Output:

Output-Return Value

Explanation: The calculateArea function computes the product of $length and $width, and its return statement sends this calculated value back, which is then captured by the $area variable.

Types of Functions in PHP

Functions in PHP are mainly divided into two sections: Built-in functions and User-Defined functions. In this section, we will understand both of these functions, along with anonymous functions and arrow functions.

1. User-Defined Functions in PHP

These functions are created by the users themselves. They code everything from the return type, parameters, and name, to logic, etc. User-defined functions give a user complete control and freedom over the program they define.

2. Built-in Functions in PHP

These are ready-to-use functions that come with the PHP package. Users can simply call these functions and utilize their functionality. 

Some common built-in functions in PHP are

  • strlen(): This built-in function returns the length of the string. 
  • session_start(): This built-in function starts a new session or resumes an existing one.
  • array_push(): This built-in function adds an element to the end of the array.
  • date(): This returns the date and time when the function was called.

3. Anonymous Functions in PHP

There is a function in PHP known as the anonymous function. It is also known as closures. These functions have no name. This function can be used to pass functions as arguments inside other functions. 

Syntax:

function ([parameters]) use ([variables from parent scope]) {
    // Function body
    // ...
    return [value]; 
};
  • There is no function name in anonymous functions. 
  • use ([variables from parent scope]): This is unique to anonymous functions. It allows you to implicitly capture variables from the parent scope by value. These variables are passed by value. 
  • An anonymous function ends with a semicolon after the closing curly brace.

Code:

<pre>
<?php
$add = function($a, $b) {
    return $a + $b;
};
echo $add(5, 3) . "n";
?>

Output:

Output - Anonymous Functions

Explanation: An anonymous function is assigned to the $add variable, which then behaves like a regular function, taking two arguments and returning their sum.

4. Arrow Functions in PHP

This function in PHP was introduced in PHP 7.4. It is similar to an anonymous function. The only difference is that it is written in one line. It is defined using the fn keyword.

Syntax:

fn([parameters]) => expression;

The arrow operator separates the parameters from the expression.

Code:

<?php
$numbers = [1, 2, 3, 4, 5];
$factor = 2;
$doubledNumbers = array_map(fn($n) => $n * $factor, $numbers);
print_r($doubledNumbers);
?>

Output:

Output - Arrow Function

Explanation: The array_map function applies the concise arrow function fn($n) => $n*$factor to each number in the $numbers array, doubling each value and implicitly capturing $factor.

Get 100% Hike!

Master Most in Demand Skills Now!

Understanding Variable Scope in Functions in PHP

The variables that are described inside the function are local. This means that they cannot be accessed or modified from outside the function. In PHP, a variable declared outside of a function is also not accessible inside the function. 

To access external variables inside a function or make the variables inside the function accessible to others, you must use the keyword global before declaring a variable. If you are using a variable inside a function, you should define the variable outside and give a reference inside the function.

Code:

<?php
$globalVar = "I'm a global variable!";
function testScope() {
    global $globalVar;
    $localVar = "I'm a local variable!"
    echo $localVar . "n";
    echo $globalVar . "n";
}
testScope();
echo $globalVar . "n";
echo $localVar . "n"; 
?>

Output:

Output - Variable scope

Explanation: Here, the function can access variables defined inside it ($localVar), but not outside. Conversely, variables defined outside a function ($globalVar) are accessible outside, but variables defined inside ($localVar) are not.

Error Handling in Functions in PHP

PHP displays error messages by default, but they are short and do not explain the whole situation. Special functions in PHP can be used to enhance the error messages for developers and users to better understand the situation. These functions are called error-handling functions. Let us see this.

We will write a code that divides an integer by zero.

Code:

<?php
echo 10 / 0;
?>

Output:

Output - Error Handling PHP Default

Explanation: In this code example, the default error was shown. 

Now, let us define an error-handling function to give a proper message to the user, informing them how to avoid this error.

Code:

<?php
$divisor = 0;
if ($divisor === 0) {
    die("Application Error: Cannot divide by zero. Please ensure the input for the divisor is a non-zero value.");
}
echo 10 / $divisor;
?>

Output:

Output - Error Handling function

Explanation: Here, we told the user to input a non-zero value. This way the user now has information on how to avoid this error as well.

Best Practices For Creating Functions in PHP

  • Use a proper, descriptive name for the function, something that will give a hint of what the function does. For example:isEmpty(), echo(), array_pop(), isValidEmail(), sendNotificationEmail() and many more.
  • Avoid using  too many parameters inside a function. Try to keep the number of parameters to a minimum. Too many parameters can make the function harder to read and maintain.
  • Make sure that the function performs a specific task
  • When dealing with data manipulation and modification, always ensure that there is a return statement so that the modified data structure can be stored somewhere. 

Practical Example of Functions in PHP

Let us understand how functions can be created to solve various problems.

Example 1: Anagram of a String

We will write a function to check whether two strings are anagrams of each other or not. This function will take two parameters of string datatype. Anagrams are words or phrases formed by rearranging the letters of another, using all the original letters exactly once.

Code:

<?php
function areAnagrams(string $str1, string $str2): bool {
    $cleanStr1 = strtolower(str_replace(' ', '', $str1));
    $cleanStr2 = strtolower(str_replace(' ', '', $str2));
    if (strlen($cleanStr1) !== strlen($cleanStr2)) {
        return false;
    }
    $charCounts1 = count_chars($cleanStr1, 1);
    $charCounts2 = count_chars($cleanStr2, 1);
    return $charCounts1 === $charCounts2
}
echo "Is 'listen' an anagram of 'silent'? " . (areAnagrams("listen", "silent") ? "Yes" : "No") . "n";
echo "Is 'Debit Card' an anagram of 'Bad Credit'? " . (areAnagrams("Debit Card", "Bad Credit") ? "Yes" :
"No") . "n";
echo "Is 'hello' an anagram of 'world'? " . (areAnagrams("hello", "world") ? "Yes" : "No") . "n";
?>

Output:

Output - Example 1

Explanation: The areAnagrams function normalizes both strings by making them lowercase and removing spaces, then compares their character frequency counts to determine if they are anagrams.

Example 2: First Non-Repeating Character

In this example, we will write a function that returns the first non-repeating character in a string. It will take only one parameter which is a string. If all the characters repeat, it will return an empty string. 

Code:

<?php
function findFirstNonRepeatingChar(string $str): string {
    if (empty($str)) {
        return "";
    }
    $charCounts = [];
    $chars = str_split($str);
   foreach ($chars as $char) {
        $charCounts[$char] = ($charCounts[$char] ?? 0) + 1;
    }
    foreach ($chars as $char) {
        if ($charCounts[$char] === 1) {
            return $char;
        }
    }
    return "";
}
echo "First non-repeating in 'swiss': " . findFirstNonRepeatingChar("swiss") . "n";
echo "First non-repeating in 'teeter': " . findFirstNonRepeatingChar("teeter") . "n";
echo "First non-repeating in 'aabbcc': " . findFirstNonRepeatingChar("aabbcc") . "n";
echo "First non-repeating in 'apple': " . findFirstNonRepeatingChar("apple") . "n";
echo "First non-repeating in '': " . findFirstNonRepeatingChar("") . "n";
?>

Output:

Output - Example 2

Explanation: This code uses a function to identify and return the first character that appears only once in each given string.

Example 3: Find the Largest Element in an Array

In this example, we’ll write a function that finds the largest element in an array of numbers. It will take only one parameter: an array of integers. If the array is empty, it will return null.

Code:

<?php
function findLargestElement(array $numbers): ?int {
    if (empty($numbers)) {
        return null;
    }
    $largest = $numbers[0]; // Assume the first element is the largest initially
    foreach ($numbers as $number) {
        if ($number > $largest) {
            $largest = $number; // Update if a larger element is found
        }
    }
    return $largest;
}
echo "Largest in [1, 5, 2, 8, 3]: " . findLargestElement([1, 5, 2, 8, 3]) . "n";
echo "Largest in [100, 20, 50, 70]: " . findLargestElement([100, 20, 50, 70]) . "n";
echo "Largest in [7]: " . findLargestElement([7]) . "n";
echo "Largest in []: " . (findLargestElement([]) ?? "null") . "n"; // Handles null output
?>

Output:

Output - Example 3

Explanation: This code defines a function to efficiently scan an array of numbers and return the highest value found, or null if the array is empty.

Conclusion

In this article, we learned and understood functions in PHP. We understood how to have control over our program’s functionality and tasks by utilizing user-defined functions. We caught a glimpse of various built-in functions. We explored several key points to consider when creating a function to ensure a smooth interpretation. We explored examples that were better solved after defining our functions. In conclusion, functions help improve both code efficiency and the development process. To become an excellent developer, you should master writing fast and efficient functions in PHP.

Convert an array to a string in PHP using the implode() function for easy data handling.

PHP Functions – FAQs

Q1. What are PHP functions?

You can use PHP functions to group reusable code that performs specific tasks. They help reduce repetition and improve code organization.

Q2. What are the 5 functions of string in PHP?

You can use string functions like strlen(), strtolower(), strtoupper(), strpos(), and substr() to manipulate and analyze string values in PHP.

Q3. What are the types of functions in PHP?

You can create built-in, user-defined, anonymous, and arrow functions in PHP, each serving different purposes in coding.

Q4. What are the 4 built-in functions in PHP?

Common built-in PHP functions include echo(), strlen(), isset(), and array_merge(), used for output, string length, variable checks, and array operations.

Q5. What is PHP used for?

You can use PHP to build dynamic web pages, handle forms, manage databases, and run server-side scripts for websites and applications.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner