Loading...

PHP Functions


In php a function is a block of code statements which provides a useful functionality in the program.
we call or invoke the function by using function name (with parenthesis and semi-colon).
note : a function name should start with name or underscore only.

the syntax is :
function functionName(){
   // statements to be executed
}
for example :
        	    	     			    		    	
<?php
    function add(){
        $a = 10;
        $b = 20;
        $c =  $a + $b;
        echo "Addition of two number is : $c";  
    }

    add();  // call the function 
?>        	    	     			    		    		
        	    	     			    		    	
        	    	     			    		    
Output :
Addition   of   two   number   is   :   30

Function Parameters or Arguments

In php we can pass parameters or arguments (information variables) to the functions. we can pass as many parameters as we want in our function.
the syntax is :
function functionName(parameter1, parameter2){
    // statements to be executed.
}
for example :
        		     					            	
<?php
    function studentName($name){
      echo "student name is : $name";
   } 

   studentName("Harry");
?>        		     					            		
        		     					            	
        		     					            
Output :
student   name   is   :   Harry

Default Parameters or Arguments

In php default parameters or arguments is used when we used a function without pass a parameter value in it. but, it takes the default values.
the syntax is :
function functionName(parameter1 = value){
    // statements to be executed.
}
for example :
        		     					            	
<?php
    function setProductCategory($name = "Electronics"){
      echo "the product category is : $name";
   } 

   setProductCategory();
   setProductCategory("Mobiles");
   setProductCategory("TV");
?>        		     					            		
        		     					            	
        		     					            
Output :
the   product   category   is   :   Electronics
the   product   category   is   :   Mobiles
the   product   category   is   :   TV