PHP Functions

The function in PHP is a very important element. With the help of Function, many major complex problems in PHP can be easily solved, and by using the function, the length of the code is also greatly reduced.

The function in PHP is used to reduce the duplication of code and the clarity of the code is improved by the use of the function. The function also reduces complex problems in simple pieces.

PHP Function Example

<!DOCTYPE html>

function msg() {
    echo "This is php function example";




This is php function example

Types of PHP Functions

  • PHP User Defined Functions
  • PHP Built-in Functions
  • PHP Anonymous Functions

PHP User-Defined Functions

User-Defined Function is created by the user.

Until the function is called, the function code is not executed.

Function in function_name, parameters and return value are these three important parts.

Function name can not be named for any loop, statement or any predefined function.

The function is incase-sensitive.

The name of the function is started by underscore or by any letter.


function function_name () {
// statement;


<?php function func() {     echo "Welcome to Tutorials Track"; } func(); // calling the function ?> 


Welcome to Tutorials Track

Example for User-Defined Function with arguments/parameters

Here, two parameters have been passed in the program’s parentheses. Multiple parameters are seperate with the comma (,). If the programmer wants to pass any number of parameters.


function add($a,$b) {
return $a + $b;

$r = add(2,3);
echo "Addition is: " . $r . "<br>";


Addition is: 5

PHP Built-in Functions

Provides some built in functions for PHP programmers. These functions make the programmer work even easier. A list of some common built-in functions is being given below.

_construct()Constructor for classes.
mysqli_connect()Connect to MySQLi Database.
date()Prints current date.
count()Used to count number of character in strings.
file_exists()Checks whether a file exists.

PHP Anonymous Functions

PHP has added new functionality functions called anonymous function. These functions are just body, they do not have a name. These functions can be used between any expression. For this, use function keyword. Anonymous function is being given below.


<?php $str = function($name) {     echo("PHP ", $name); }; $str('Function'); ?> 


PHP Function