Home >>PHP Object Oriented >Find sum of n numbers using function

Find sum of n numbers using function


Find sum of n numbers using function

Create a Parametrized function in which numbers entered by user convert into array and find the sum.

<?php
function add($arr)
{
$num =    explode(",",$arr);
foreach($num as $v)
{
$sum+=$v;
}
echo $sum;
}
//call function add
if(isset($_GET['add']))
{
add($_GET['n']);
}
?>


<form>
enter your number separated by (,)<input type="text" name="n"/><br/>
<input type="submit" value="+" name="add"/>
</form>

Output 15
enter your number separated by (,)

The given example is used find the sum of n numbers which we entered in a textbox separated by , all the values are passed as a string to test function ,where by using explode function it is converted into an array and assigned in num variable. than by using foreach the values are retrieved 1 by 1 and they are being added in a sum variable and at last this variable is used to print the value of the sum of n numbers that are entered by the user.


Popular Tutorials