How to PHP Scripting- PHP Functions

The power of the PHP language is a large number of built-in functions (more than 1000 built-in functions.) You can also possible to create your own functions. In this PHP tutorial, we will create our own functions.PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of a parameter and does some processing and returns a value.

A function will only be executed if a function is called by another piece of code. A user-defined function is a block of statements that can be used repeatedly in a program. It will not execute immediately when a page loads and executed by a call to the function.

 

Creating and Calling Functions.

A function is created with the function keyword.

 

Syntax
     function functionName() {
         code to be executed;
     }

The function name should reflect what the function does and can start with an underscore or letter. A number is not allowed.

 

Example
     <?php
         function ourFunction(){ // declaring Function
              echo "White";
         }
         echo "My car has the color ";
         ourFunction(); //invoking function
     ?>

 

Output
       My car has the color White

 

PHP Functions with Parameters

Function with parameters would be able to add some extra functionality. You can pass as many as parameters your like. These parameters work like variables inside your function.

 

Syntax
     function myFunc($FirstParameter, $SecondParameter){
         // Code to be executed
     }

 

Example
     <?php
      function getSum($num1, $num2){
        $sum = $num1 + $num2;
        echo "Sum of the two numbers $num1 and $num2 is : $sum";
      }
      getSum(10, 20);
     ?>

 

Output
      Sum of the two numbers $num1 and $num2 is : 30

 

PHP Default Argument Value

You can set a parameter to have a default value if the function’s caller doesn’t pass it.

 

Example
     <?php
          function printMe($param = NULL) {
             print $param;
          }
          printMe("This is test");
          printMe();
     ?>

PHP Functions returning value

A function can return a value back to the script that called the function using the return statement. The value may be of any type, including arrays and objects.

 

Example
     <?php
     function sum($a, $b) {
         $c = $a + $b;
         return $c; // return value of c
     }
     echo "5 + 10 = " . sum(5, 10) . "<br>";
     echo "4 + 8 = " . sum(7, 13) . "<br>";
     ?>

Muhsin Yakkiparamban

Muhsin Yakkiparamban is the co-founder of Lauyou Learning. Muhsin holds Bachelor Degree in Civil Engineering from KMCT Calicut.

You may also like...