A function is a statement or block of code use for perform certain task or operation.
A function is not execute when we run a program. A function is execute only when we call the function.
function functionName(){
// Code to be executed
}
There is two type of function in PHP:
In php there is almost 1000 built in function exists.We only have to use this as per our requirements.
print_r(), strlen(), fopen(),mail() function etc.
A user defined function is create by the user.
Here writeMsg() is a user defined function.
As the function is separate from other script of function we can easily reused the function for other application.
Less code means because you don't need to write the logic many times. Once you write a function we have to only call to that function where it needed.
Easy to understand in the sense that as the logic inside the function we have to only know the function name . Once we get the function name we can find the logic and easily modify it.
We can easily find the error if we use function because it is separate from php programming.By find where the function call we get the function name and easily solve the error.
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
<!DOCTYPE html>
<html>
<body>
<?php
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
getSum(20, 30);
?>
</body>
</html>