PHP Function


 

PHP Function

In this tutorial we will study about user-defined functions, declarations part, how to call a function, recursive function etc. Examples in this tutorial will make it more clear.

In this tutorial we will study about user-defined functions, declarations part, how to call a function, recursive function etc. Examples in this tutorial will make it more clear.

User Defined Functions

In modern days programming language, functions are eternal part of a program, with the help of functions a program is become more manageable, robust.

A general format of the function in PHP is as follows:

function <function name> (<list of parameters>)

With the help of functions we can reduce time and effort, all we need to do is create a function and put the necessary coding into it and we can call this function from anywhere of the program. With the help of return statement we can return values to the calling portion.

One function can be called number of times, and one function can call itself too, this technique is called recursion. 

Example:

<?php

function add($a,$b){

return $a+$b;}

$c=add(12,39);

echo "Addition is:".$c;

?>

 

Output:

Addition is:51

 

Example:

<?php

function fact($b){

if($b==1)

return 1;

else

return($b* fact($b-1));

}

echo "Factorial of 6 is:".fact(6);

?>

Output:

Factorial of 6 is:720

Ads