PHP Functions

PHP Functions is used to reuse php code. PHP Functions contains a piece of code which takes one or more parameter as input and make some processing on it and returns a value.

PHP provides more than 1000 of built-in library functions. But also we can create user defined custom function. PHP Functions reduces our writing code time by reusing same logic code .

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be used many times.
Less Code: It saves a lot of code to rewrite it again. You can write the logic only once and reuse it by the use of function.
Easy to understand: PHP functions separate the programming logic. So you can easy understand the flow of the application because every logic is separated in the form of functions.

Creating PHP Function

A user define function must start with keyword function and all the PHP code should be put inside { and } braces.A function will be executed by a call to the function.

PHP Syntax :

    function function_name(){  
           //code for programming logic. 
    } 

PHP Example : 

<?php  
        function sitetitle() //user defined function
        {  
             echo "Welcome to learning system";  
        }  
        sitetitle();//calling function  
    ?> 

Output:

Welcome to learning system 

PHP Functions with Parameters

you can pass your parameters inside a function.You can add as many arguments as you want, just separate them with a comma. You can pass arguement by Call by Value (default), Call by Reference, Default argument values and Variable-length argument list.

PHP Example : 

<?php
         function sub($num1, $num2) {
            $sub = $num1 - $num2;
            echo "Substraction of the two numbers is : $sub";
         }
         
         sub(800, 546);
?>

Output:

Substraction of the two numbers is : 254

PHP Functions return value

A function can return a value using the return statement.

PHP Example : 

<?php
         function sub($num1, $num2) {
            $sub = $num1 - $num2;
            return $sub;
         }
         
         $return_sub=sub(230, 146);
         echo "Substraction of the two numbers is : $return_sub";
        
?>

Output:

Substraction of the two numbers is : 84

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

19442