Why functions are being used in PHP?

You are currently viewing Why functions are being used in PHP?

Why functions are being used in PHP?

Functions are an essential part of PHP programming.PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. Functions can be reused multiple times in a program, reducing the time and effort of repeating a single code.PHP provides us with two major types of functions:

Built-in functions : PHP provides us with huge collection of built-in library functions. These functions are already coded and stored in form of functions. To use those we just need to call them as per our requirement like, var_dump, strlen(), print(), date()and so on.

User Defined Functions : Apart from the built-in functions, PHP allows us to create our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply calling it.

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
PHP Functions Example-:

				
					<?php  
function sayHello(){  
echo "Hello PHP Function";  
}  
sayHello();   // call the function
?>  

				
			
				
					Output :
Hello PHP Function

				
			

Function Parameters or Arguments

We can pass the information in PHP function through arguments.An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
Let’s see the example to pass two argument in PHP function.

				
					<?php  
function myFunction($name,$age){  
echo "Hello $name, you are $age years old<br/>";  
}  
myFunction("Vishal",27);  
myFunction("Sarika",26);  
?> 

				
			
				
					Output:
Hello Vishal, you are 27 years old
Hello Sarika, you are 26 years old

				
			

PHP Function: Returning Value

To let a function return a value, use the return statement:
Let’s see an example of PHP function that returns value.

				
					<?php  
function Square($n){  
return $n*$n;  
}  
echo "Square of 25 is: ".Square(25);  
?> 

				
			
				
					Output:
Square of 25 is: 625

				
			

Leave a Reply