Functions in PHP |
We can use a function in PHP to execute a specific task or a set of tasks. Function is used when a specific code is used again and again. It is better to keep the code inside a function and call the function to perform the same task. We can pass variables to a function and after processing the function will return the value to the main script. So a function is a set of or block of code to do a particular task. PHP has got many built-in functions for us to use. These functions are available by default to us and we can use them at any time without declaring them. We will discuss on user defined functions here. We will learn how to declare a function, pass a variable or an array and how to return variables or array to main script or calling script. Let us see how to define a function.
<?
function my_function($var1,$var2){
// Place to enter code here.
print "Value of first variable = $var1";
print "<br>";
print "Value of second variable = $var2";
}
/*The above lines are a declaration of a function which takes two inputs. We can call a function like this.
*/
my_function("first value", "Second value");
?>
You can see above we have kept the code inside a function and call it from our main script. Two variables we have passed to the function and displayed them using print command. Here print is a built-in function of PHP.
|