You are currently viewing PHP User Defined Functions

PHP User Defined Functions

A function is a block of code which we use to perform a specific task repeatedly in a program.

Functions allow us to save the time without typing the same pace of code again and again.

A function will not execute as soon as the program starts.

Therefore, to execute a function we need to call it.

The standard Syntax for a PHP user defined function.

function functionName() {
    code to be executed;
}

The function name should start with a letter or an underscore and it’s case sensitive.

To call a function, type the function name and the parenthesis.

functionName();

The given below is a simple PHP program to demonstrate.

<?php
 function MyFirstName(){
   echo "Shehan" ;
}
echo "My First Name is ";
MyFirstName();
?>

Output

My First Name is Shehan

PHP Function Arguments

Information can be conveyed to functions through arguments. Arguments are like variables, and you can add many arguments by separating them with a comma inside the parentheses.

The function Addition has two arguments $number1, $number2 and we will call the function while passing the value of the variables $num1 and $num2. Then the function will echo the sum of the two values.

<?php
$num1 = 20;
$num2 = 30;
function Addition($number1,$number2){
       echo $number1 + $number2;
}
 Addition($num1, $num2);
?>

Output     

50

PHP Default Argument Value

The following example shows you how to use PHP function with default arguments.

The function Addition has two arguments $number1, $number2 with the default values 10 and 20.

Then we have called the function two times and the time we called the function without passing any values has taken the default values 10 and 30. Hence, the output of the second calling is 40.

<?php
function Addition($number1 = 10,$number2 = 30){
       echo $number1 + $number2 .'<br/>';
   }
Addition(10, 20);  // Here we have passed the two values
Addition();  // Here we haven’t passed any values so it will take the default values 10 and 30
?>

Output

30
40

PHP Functions – Returning values

A function can return a value by using the return statement.

<?php
function Addition($number1,$number2){
        $result = $number1 + $number2;
                   return $result;
}
echo Addition(10, 20);
?>

Output

30

Leave a Reply