PHP – function with real time example



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:

  1. Built in function
  2. User defined function

Built in function

In php there is almost 1000 built in function exists.We only have to use this as per our requirements.

Example:

print_r(), strlen(), fopen(),mail() function etc.

User Defined function

A user defined function is create by the user.

Example:

 

<?php function writeMsg() { echo "Hello world!"; } writeMsg(); ?>

Here writeMsg() is a user defined function.

Advantages

  1. Code reusability
  2. Less code
  3. Easy to understand
  4. Easy to find error

Code reusability

As the function is separate from other script of function we can easily reused the function for other application.

Less code

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

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.

Easy to find error

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.

Example:

<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>

Function with parameter:
Syntax

function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}

Example

<!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>