Functions in PHP

In this tutorial, we will learn about the concepts of functions in PHP. A function is a block of reusable code that performs a specific task. It will only execute when “someone” calls it. If you do not call it, the code inside the function will never execute.

To understand what exactly a function does in PHP or any other languages, let us consider an example of a soda-making machine. To get flavored soda from a soda machine, we need to add essential ingredients such as essence and mineral water.

The machine then processes these raw materials and gives the desired flavor. In the same way, you can use functions to get the desired output. The output entirely depends on the logic of code you write in it.

A function in PHP performs the following tasks:

  • Accepts values: A function can take input values, known as arguments, passed to it.
  • Processes them: The function executes the block of code specified inside it.
  • Performs an action: After the complete execution, the function returns an output or performs a specific task.

However, returning a value from a function is an optional feature. You can create a function to perform an action without returning a value. The output of one function can also acts as the input for another function. Additionally, you can directly print the output of a function to the command-line or browser.

Why do You Need to Use Functions in PHP


There are the following reasons of using functions in PHP program. They are:

(a) Code Reusability: Functions allow you to reuse code across different parts of an application program. Once you write the code inside the function and test it, you can use the same function multiple times in a program as per the requirement. In simple words, write the code once and use it several times.

(b) Improved Readability: Organizing your PHP code into functions makes it simple to read and understand. It improves the clarity of the code written in a program.

(c) Easy Maintenance: Debugging and updating code becomes easier when you break up a long and complex code into functions. It makes the code modular.

You can debug each segment of the code one at a time and then assemble them into a working whole. If you need to make a change in the code, you can easily update it in one place. Thus, the maintenance of code becomes easy.

(d) Reduced Redundancy: In PHP, functions help to reduce redundancy by avoiding code duplication. You can avoid the repetition of frequently required code using functions.

By writing frequently required code within a function, you can reuse the specified code multiple times throughout your program without rewriting it. This not only saves your time but also enhances maintainability and reduces the likelihood of errors.

Types of Functions in PHP


There are two types of functions in PHP:

  • Built-in functions
  • User-defined functions

Built-in Functions:

Built-in functions in PHP are pre-written functions that are part of PHP by default. These functions have a predetermined functionality that doesn’t change. PHP provides the built-in functions to perform common tasks, such as string manipulation, array operations, mathematical calculations, file handling, and many more.

PHP provides an extensive library of built-in functions, with over 1,000 functions available that we can directly use within the script to perform a wide range of tasks. Some examples of built-in functions are:

  • strlen(): Calculates the length of a string.
  • array_merge(): Merges two or more arrays.
  • date(): Formats a local date and time.
  • file_get_contents(): Reads the content of a file into a string.

Explore this comprehensive PHP reference guide for a detailed overview of all PHP built-in functions, complete with examples and usage tips.

User-defined Functions:

As the name suggests, user-defined functions are custom functions that are created by a user or PHP programmer to perform a specific task. They allow you to create your own functions in a program as per requirements.

User-defined functions allow you to organize, modularize, and reuse your code effectively. You can completely customize these functions and specify exactly what the function does. Look at the below syntax to define user-define functions.

Syntax to Define Functions in Python


The general syntax to declare user-defined functions in PHP is as follows:

function functionName($para1, $para2, . . .  $paran) {
   // Statement(s) or Code
      return $value; // Optional
}

In the syntax of function, the function definition begins with a keyword function, followed by the name of the function, parentheses (()), and then a pair of curly braces {} enclosing the body of the function. Let’s break down these components:

Components of PHP Functions:

Components of functions in PHP

1. Keyword function:

The definition of a function starts with the keyword ‘function’ that defines the function in PHP.

2. functionName:

This is the name of a function that follows the keyword function. All functions must have unique function names or identifiers because PHP does not support the function overloading.

For example, you cannot define two functions with the same name display_func. It is an excellent practice to name your function according to the work it performs.

(3) Function Parameters:

The $para1, $para2, . . . . . $paran is a comma-separated list of parameters that is defined inside the parentheses following the function’s name. These parameters are called formal parameters or simply parameters, which allow you to pass values into a function.

A function can have more than one parameter separated by commas inside the parentheses. However, they are optional. The formal parameters should always be placed inside the parentheses.

The formal parameters are basically local variables within a function. You can name them anything you like. When a function is called, the actual values (arguments) are passed to these parameters.

(4) Statement(s):

The function’s body consists of one or more valid statements. When the function gets called, the statements or code inside the function’s body executes.

(5) Return statement:

A return statement ends the execution of a function and returns a value of any type, such as string, integer, array, object, etc. to the calling code. However, it is optional. If you do not define the return statement inside the function’s body, the function automatically returns NULL by default.

(6) Curly braces: The opening curly brace { marks the beginning of the function’s code block, and the closing curly brace } marks the end of the function.

Rules for Defining Functions in PHP


There are the following rules for defining functions in PHP that should you keep in your mind. They are as:

  • Function names must start with a letter or an underscore (_). The first character of a function name cannot be a number or any other symbol.
  • Function names can contain letters, numbers, and underscores. For example: myFunction, my_function, or function123.
  • Function names are NOT case-sensitive in PHP. Calling a function as myFunction() or MYFUNCTION() will refer to the same function.
  • You cannot use reserved keywords as function names. For example, keywords like while, for, if, and class cannot be used as function names.
  • Function names can include numbers but cannot begin with one. For example: function1() is valid, but 1function() is invalid.
  • There is no restriction on the length of a function name. You can define the name of a function of any reasonable length.
  • You can use underscores to separate words for readability. For example: function_name() or get_user_details().
  • Spaces are not allowed between words in the function name. Use underscores instead.
  • It is common practice (but not mandatory) to write function names in lowercase. For example, my_function() is preferred for consistency, though MyFunction() is still valid.

Calling Functions in PHP


The function does not do anything until you call it. In other words, the code or statements inside the function will execute when you call it. In PHP, you can call a function anywhere in the program after it has been defined. You can also trigger a function call in response to an event, such as when a user interacts with a button or submits a form.


To call a function in PHP, you simply use the function name followed by parentheses (). If the function accepts arguments, you pass them inside the parentheses. Here’s the basic syntax:

<?php
functionName(arguments);
?>

Here, arguments are the actual values that are passed to the functions when called them. Inside the function, we use these values through the parameters to perform a specific task.

Examples based on PHP Functions


Example 1: Let’s write a PHP program in which we will define a function and call it without passing arguments.

<?php
// Defining a function named sayHello.
function sayHello() {
   echo "Hello, World!";
}
// Calling a function.
sayHello();
?>
Output:
      Hello, World!

In this example, we have created a function named sayHello() and called it.

Example 2: Let’s write a PHP program to calculate the sum of two numbers.

<?php
function sum(){
  $x = 20;
  $y = 30;
  $z = $x + $y;
  echo "Sum = " . $z;
}
sum(); // calling the function.
Output:
      Sum = 50

Example 3:

<?php
$x = 10;
$y = 50;
function sum(){
   global $x;
   global $y;
   $z = $x + $y;
   echo "Sum = " . $z;
}
sum(); // calling the function.
?>
Output:
      Sum = 60

PHP Function Using Arguments


When you call a function, you can pass along some values to it. These values are called arguments or formal parameters. Let’s take an example on it.

Example 4:

<?php
// Function with one formal parameter.
function greet($name) {
    echo "Hello, $name!";
}
// Calling the function with an argument.
// Here, "Saanvi" is an argument passed to the function.
greet("Saanvi");
?>
Output:
      Hello, Saanvi!

In this example, we have defined a function named greet() with one formal parameter “$name”. Then, we have called it by passing an argument “Saanvi” to the function.

Example 5:

<?php
function add($a, $b) {
   $c = $a + $b;
   echo $c . "\n";
}
function subtract($a, $b) {
   $c = $a - $b;
   echo $c . "\n";
}
function multiply($a, $b) {
   $c = $a * $b;
   echo $c . "\n";
}
function divide($a, $b) {
  if ($b != 0) {
     $c = $a / $b;
     echo $c;
  } else {
     echo "Division by zero is not allowed.";
  }
}
// Calling the functions by passing two arguments.
add(10, 20);
subtract(20, 10);
multiply(40, 50);
divide(50, 10);
?>
Output:
      30
      10
      2000
      5

Example 6: Let’s write a PHP function to calculate the sum of two numbers by passing different values. Here, we will reuse the same function multiple times by passing different values.

<?php
// Declare a function to calculate the sum of two numbers
function calculateSum($a, $b) {
   $sum = $a + $b;
   echo "Sum of $a and $b = $sum \n";
}

// Call the function multiple times with passing different values.
calculateSum(10, 20);
calculateSum(5, 15);
calculateSum(30, 40);
?>
Output:
      Sum of 10 and 20 = 30
      Sum of 5 and 15 = 20
      Sum of 30 and 40 = 70

Function with Default Parameter Values


PHP also allows you to assign default values to the function parameters. This means that if you do not pass an argument to that parameter when you call the function, the default value will be used. You can assign a default value to a parameter using the = operator inside the parentheses followed by the function’s name. Let’s take some examples based on it.

Example 7:

<?php
function greet($name = "Tripti") {
   echo "Hello, $name! \n";
}
// Calling function without passing argument.
greet();

// Calling the function with passing argument.
greet("Saanvi");
?>
Output:
     Hello, Tripti! 
     Hello, Saanvi!

In this example, when we have called the greet() function without passing any argument, the $name parameter defaults to “Tripti”.

Functions with Named Arguments in PHP


PHP also supports named arguments, which allow you to pass arguments to a function by explicitly specifying the name of the parameter along with its value. This feature was added in PHP 8.0 version.

You can pass them in any order as long as the parameter names match those defined in the function. However, you can skip optional arguments and only specify the ones you need by name. Let’s take some examples based on this feature.

Example 8:

<?php
function greet($name, $greeting = "Hello") {
   echo "$greeting, $name!";
}
// Using named argument.
greet(name: "Saanvi", greeting: "Hi");
?>
Output:
      Hi, Saanvi!

Example 9:

<?php
function greet($name, $message = "Welcome", $punctuation = "!") {
    echo "$message, $name$punctuation\n";
}
// Using named arguments
greet(name: "Saanvi", punctuation: "!!");
?>
Output:
       Welcome, Alice!!

You can combine positional arguments (passed by position) with named arguments, but positional arguments must come first.

Example 10:

<?php
function createProfile($name, $age, $city = "Dhanbad") {
    echo "Name: $name, Age: $age, City: $city\n";
}

// Mixing positional and named arguments
createProfile("Saanvi", age: 18);
?>
Output:
      Name: Saanvi, Age: 18, City: Dhanbad

In this example, “Saanvi” is a positional argument because it is passed based on its position in the parameter list. $name is the first parameter in the function definition. Note that positional arguments are passed based on the order of parameters defined in the function.

On the other hand, age: 30 is a named argument because the parameter name (age) is explicitly specified along with its value 30.

Function Hoisting in PHP


In PHP, you can call functions before you defined them. This is because PHP scans (i.e. reads) the entire script file for function definitions during parsing phase before it starts to execute the main body of the script. This process is knows as function hoisting.

Key Points About Function Hoisting:

  • Function definitions are stored in memory during the parsing phase, making them accessible throughout the script.
  • This applies only to functions which are defined in the global scope. Functions inside conditional statements or loops may not be hoisted if the condition is not met.

Example 11:

<?php
// Function is called before its definition.
sayGoodBye();

function sayGoodBye() {
   echo "Goodbye, world!";
}
?>
Output:
      Goodbye, world!

However, it is recommended for the best practice that you define functions at the beginning of your script or in separate file and then call them when needed. This practice makes the code clearer and more readable.

Key Points about PHP Functions

  • PHP doesn’t support function overloading. Therefore, you can’t define more than one function with the same name.’
  • PHP doesn’t allow to redefine or undefine once the function is declared.
  • It supports functions with a varying number of arguments using the … operator. This is called variadic function.
  • Functions in PHP support default arguments that are used when the arguments are not provided during the function call.
  • PHP also supports named arguments, allowing you to pass values to a function by specifying the parameter name.
  • A function must be explicitly called in the script for its code to execute.
  • You can call the same function several times within a script.
  • A function can contain PHP code, calls to other functions, or even class definitions.