Home > DeveloperSection > Articles > PHP User Defined Functions

PHP User Defined Functions


PHP PHP 
Ratings:
0 Comment(s)
 3445  View(s)
Rate this:

PHP User Defined Functions

In this article I will show you how to create your own function. To keep the script from being executed when the page loads, you can put it into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page.

Let’s we have an example, how to implement PHP functions.

Syntax:

function function_Name()

 {

   code to be executed;

 }

Note: The function name can start with a letter or underscore (not a number).

Example: Creating function with no parameter

<html>

  <head>

       <title> Function Test</title>

  </head>

  <body>

                     <?php

                // Creating function with AdditionNum name for adding two integer value

                            function AdditionNum()

                            {

                               $num1  = 45;

                                  $num2  = 45;

                                  print "Addition of two number is : ".($num1+$num2);

                            }

                            

                           echo "This is function value : "."</br>";

                     // Calling function

                           AdditionNum();

                                 

       ?>

 

  </body>

 

</html>

Output:

PHP User Defined Functions

Example: Creating function with parameter.

Let’s we have an example, how to create a function with parameter.

Syntax:

function functionName(param1, param2,...)

 {

   code to be executed;

 }

<html>

  <head>

       <title> Function with parameter</title>

  </head>

  <body>

       <?php

              functionAdditionNum($num1,$num2)

                 {

                     print "Addition of two number is : ".($num1+$num2);

                 }

                            

              echo "This is function with parameter : "."</br>";

       // Calling function

              AdditionNum(12,13);

                                 

       ?>

 

  </body>

 

</html>

Output:

PHP User Defined Functions

Example: Function with ‘return’ statement.

Let’s we have an example, how to implement function with return type statement in PHP.

<html>

  <head>

       <title> Function with parameter</title>

  </head>

  <body>

              <?php

                     functionAddNum($num1,$num2)

                      {

                       return ($num1+$num2);

                      }

                // calling AddNum function            

                echo "Addition of(12 + 13) : ".AddNum(12,13);

            ?>

 

  </body>

 

</html>

Output:

PHP User Defined Functions


Don't want to miss updates? Please click the below button!

Follow MindStick