User Defined functions in PHP

Functions are the common technique in all programming languages to implement code reuse at a very subtle level. A Function is defined as a set of programming language instructions that are usually given a name that identifies the purpose of function. These set of instructions can be executed any number of times by calling the function by name.  Although PHP has a huge repository of in-built functions, you can create your own functions to use modularity and reuse of code in your applications. So here is an introduction to user defined functions in PHP.

Benefits of using User Defined Functions in PHP

  • Improves readability of a program by enclosing the set of statements in a function body and calling them by name whenever and wherever required in a program.
  • A function can be called as many times as needed.
  • It reduces the code editing efforts. If some changes are to be done in functionality of  a function, it can be done in that specific function without changing its signatures (name and argument list).
  • User defined functions help in extendible and modular development of applications.
  • User defined functions give freedom to a programmer to define and name the code to do specific tasks that may not be implemented with the help of inbuilt functions.

Syntax-User Defined Functions

The following is the syntax for creating user defined functions in PHP (words written like this are keywords)

function function-name( argument list)


Function body


To define a function you have to specify four things

  • Keyword function at the beginning.
  • Name of the function using the naming conversions used for PHP variables but without a $ sign.
  • List of arguments that you need to pass as input on which your function will execute the statements. The arguments must be written as variables preceded with a $.
  • Within the curly braces ({}) write PHP statements to implement the logic of the function to perform your desired task.

PHP stores the names of all the functions in lowercase so writing the name with some specific capitalization is not going to be considered while interpreting the code.

Example-User Defined Functions

function printMessage($name,$site)
                if (substr(date("h:i:sa"),-2)=="pm")
                                echo "Good Night $name, visit $site tomorrow";
                                echo "Good Morning $name, Welcome to $site!!";