Posted By:
9 Mar, 2014 5:29 am PDT

How to write user defined function in PHP

 How to write user defined function?

Function is block of code which can be called whenever we need to carry out certain task from that function. Function can be called many times. Function starts execution when we called it.

 

Syntax:-

function functionName(argument list)

{

            //write your function code here

}

 
 

<?php

echo "<h2 >";

         echo " To CALCULATE SUM OF THE DIGIT OF NUMBER <br ><br >";

$no = rand (100 ,99999) ;

echo " The DIGIT is";

 

dispalyNumber ( $no); // calling function

$sum = calDigitSum ( $no ); // calling function

 

         echo "Sum of DIGIT is ";

 

dispalyNumber ( $sum ); // calling function 

      function dispalyNumber ( $no) // function with argument but no return value

        {

echo " { $no } <br ><br >"; // statements 

}

                    function calDigitSum ( $num ) // function with argument and return value

{

$sum =0; // statements

$rem =0;

do{

$sum = $sum + ( $num % 10) ;

$num = $num / 10;

} while ( $num !=0) ; // condition

return $sum ; // return value

 

?>                                                        Function.php

 


Argument list is optional, it is also called parameter list. We can pass information to function through function call.

Note:- Function name cannot start with number or underscors 

 

FunctionOutput

Attachment: FUNCTION.PHP


How to write function in PHP

 

Function are the piece of code that can be used repeatedly in program.It can take input in the form of parameter and can be called anywhere in your program.

 

Syntax:

Function function_name

{

            //code

}

//To show how to use function in php.

 

<!DOCTYPE html>

<html>

<body>

<?php

function pet($name)

{

echo "Name of pet is:";

echo "$name.<br>";

}

pet("Tommy");

pet("puppy");

pet("tiger");

?>

</body>

</html>

 
/*Output of the above program is:

Name of pet is:Tommy

Name of pet is:puppy

Name of pet is:tiger

Attachment: fuction.php
Was it useful?  




Please login to reply to this problem.