PHP Functions

A function is a block of statements that can be used repeatedly in a program. It can take input as argument list and return value. PHP functions are similar to other programming languages.

There are thousands of built-in functions in PHP.

PHP User Defined Functions

PHP allows us to create our own customized functions called the user-defined functions.

You can create function in PHP as per following syntax.


function functionName() {
  code to be executed;

A user-defined function declaration starts with the keyword function.

A function name must start with a letter or an underscore. It can’t be start with numbers or special symbols.

Function names are NOT case-sensitive.


In the example below, we create a function named “writeMsg()”.

function writeMsg() {
  echo "Hello world!<br>";

writeMsg(); // call the function
writeMSG();//Checking case sensitivity
PHP User Defined Function Example Output

The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function.

The function outputs “Hello world!”.

A function will not execute automatically when a page loads. A function will be executed by a call to the function. To call the function, just write its name followed by brackets ()

Advantage of PHP Functions

Code Reusability

PHP functions are defined only once and can be invoked many times. In this way you can use same function many times.

Less Code

With the help of function, you can write the logic only once and reuse it. In this way it will reduce code size.

Easier error detection

Because, our code is divided into functions, we can easily detect in which function, the error could lie and fix them fast and easily.