In this tutorial we are going to deal with function with a return value.We have already seen two other tutorials of basic function and function with arguments. Generally we echo out the content of function inside it only,but if we want to echo out the content outside the function, we will use “return” keyword. Here, “return” keyword returns a specific value the value which can be calculated inside function that can be a string or integer value. Hence the value which is returned outside the function and is stored in any variable of the same datatype as that of variable that is being returned, can be echoed out easily.
Example:- If we want to divide two number before adding it as:-
(10, 10)/ (5, 5) = 2
Here,10 should get added with 10 and 5 should get added with 5 & then divide 20 / 10 which will give 2 as answer (Screenshot1).
Screenshot1 |
Code for function with a return value (Screenshot2):-
Screenshot2 |
<?php
function add($number1, $number2) {
$result = $number1 + $number2;
return $result;
}
add(10, 10);
?>
Output (Screenshot3):-
Screenshot3 |
In this example, I have created the function for adding two number and storing value to “result” variable and then return the value from functions. Here, it will not echo out anything in browser because its just storing value to function by return keyword.
Code for function with return value (Screenshot4):-
Screenshot4 |
<?php
function add($number1, $number2) {
$result = $number1 + $number2;
return $result;
}
echo add(10, 10);
?>
Output (Screenshot5):-
Screenshot5 |
In this example, I have created the function for adding two number and storing value to “result” variable and then return the value from functions. Here, it will echo out values via variable “sum” by calling functions.
Code for functions with return value adding and divide it(Screenshot6):-
Screenshot6 |
<?php
function add($number1, $number){
$result = $number1 + $number2;
return $result;
}
function divide($number1, $number2) {
$result = $number1/ $number2;
return $result;
}
$sum = divide(add(10, 10), add(5, 5));
echo sum;
?>
Output (Screenshot7):-
Screenshot7 |
Here,firstly we have to make two functions to add two variables and then divide them. As we seen in screenshot4 we are adding two number by calling function, passing values to variables, storing values of the result and then retrieving value of result outside the function. Similarly, for divide function too.It will work as in first (Screenshot1) (10 + 10) / (5 + 5) = 2.
In this way you can use function many time by calling and passing variables; every time functions variables will be changed which is every useful for us to reuse the functions. Its easy for the programmer as it shorts the codes in the program.
No comments:
Post a Comment
Thanks For Comment Will get you Soon..