Function

A function often accept one or more arguments, which are values passed to the function by the code that calls it. The function can then read and work on those arguments. A function may also optionally return a value that can then be read by the calling code. In this way, the calling code can communicate with the function.

Why Functions Are Useful

Functions are useful for a number of reasons:

  • They avoid duplicating code.
  • They make it easier to eliminate errors.
  • Function can be reused in other scripts.
  • Function help you break down a big project

User Defined Functions

PHP Function are similar to other programminhg language. A Fuction is the pices of code which takes one or more inputs in the form of parameter and doese some processing and a return a value.

Creating Function

Syntax:

function name($arg_1, $arg_2, $arg_n)

Example:- Simple

<?php
function UDF() #create function
{
    $message="Hello! php Developers";
    echo $message;
}
# calling the function
UDF();
?>

Example:- With Passing Argument...

<?php
function message($col) #create function
{
    $m="Hello! php Developers";
    echo "<br/><span style='color:$col'>$m.</span>";
}
# calling the function
message("green");
?>

Return Type Fuction

Example:-

<?php
function mess($n,$col)
{
    echo"<br/><span style ='color:$col'>.$n</span>";
}
    function area($l,$w)
{
$m=$l*$w;
return $m;
}
#calling the function
$message="Hello! How are you";
mess($message,"red");
$r=area(5,6);
mess("Area::".$r,"green");
?>

Conditional Function

Example:-

<?php
$test=true;
if($test)
{
    function sayhello()
    {
		echo"<br/>"."Here is conditional function";
	}
	if($test) 
	sayhello();
}
?>

Recursive Function

Example:-

<?php
function recursion($a)
{
    if($a<=20)
    {
		echo "$a\n";
		recursion($a+1);
	}
}
recursion(1);
?>