PHP Functions

A function is similar to a program that consists of a group of statements and perform a specific task. Functions are callable section of code in which you can pass data to and that function can return data to you.


Advantages of functions:

There are following advantages of functions.

  • Functions are important in programming language like PHP, because they are used to perform calculations and perform any task which are required in software development.
  • Functions are reusable. It means, once the function is written, it can be reused as and when required.
  • Functions provides modularity for programming technique. And modular techniques help to break down a complex task into simpler task.
  • Functions in a software development makes programmer easy to debug. Code maintenance becomes very easy.
  • Features of any function can be changed without affecting the others functions.
  • Using functions, you can reduce the length of the program.

Types of functions

There are two types of functions.

  • Built-in functions
  • User defined functions

Built-in functions

In PHP, there are over 1000 of built-in functions which are called directly to perform some task. These types of functions pre-defined within PHP.


User defined functions

Apart from built-in functions, you can create your own function.

  • Functions name should starts with a letter or underscore followed by any numbers or letters.
  • Function names are not case-sensitive.
  • Functions are open by ‘{‘ and closed by ‘}’ curly braces.

How to create a user defined function in PHP?

A function in php defined with the word “function” followed by function name.

function function_name()
{
    //Your code to be executed
     ...
}

Example- write a function to calculate sum of two numbers.

function sum()
{
   a = 10;
   b = 20;
   sum = a+b;
   echo sum;
}

//calling function
sum();

//result
30

Trending Topics