PHP Functions
Definition: PHP has many functions predefined, but often you will be using functions that you create yourself.
![]() | A function will be executed by a calling to that function. |
![]() | Functions are called from any where in php code. |
Creating a function is very easy, here is how:
function FunctionName()
{
code to be executed;
}
First you define the function name, and write then what the function will do. Here is an example:
function exfunction ()
{
print "Hi, This is PHP functions";
}
<?php
function myfunc()
{
echo "PHP Tutorials";
}
echo "Welcome to ";
myfunc();
?>
Output : Welcome to PHP Tutorials
Here myfunc is the function name. First it is declared at the top and write the code with in the function is 'PHP Tutorials'. After that call the function by using myfunc(). It will execute the code which is write in the function.
Functions with Parameters:
A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.
Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way. Note the terminology used - the names given in the function definition are called parameters whereas the values you supply in the function call are called arguments.
<?php
function add($a,$b) {
echo $a+$b;
}
echo "Addition of 5 and 3 is : ";
add(5,3);
?>
Output : Addition of 5 and 3 is : 8
Functions with return:
Return is used return the output value from function .
Example1:
<?php
function add($a,$b) {
return $c=$a+$b;
}
function sub($a,$b) {
return $c = $a-$b;
}
function mul($a,$b) {
return $c = $a*$b;
}
echo "Addition of 5 and 3 is : ";
echo add(5,3);
echo "Subtraction of 5 and 3 is : ";
echo sub(5,3);
echo "Multiplication of 5 and 3 is : ";
echo mul(5,3);
?>
Output:
Addition of 5 and 3 is : 8 Subtraction of 5 and 3 is : 2 Multiplication of 5 and 3 is : 15
Example2:
Find the maximum number between two numbers by using functions.
<?php
function maximum($a,$b) {
if ($a>$b)
echo $a .'is maximum';
else
echo $b .'is maximum';
}
$x = 5;
$y = 7;
maximum($x,$y);
?>
Output: 7is maximum
