Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello everyone!
i tried a lot to calculate the average with this simple html php code but it gives me error
anyone can help?

What I have tried:

<pre><body>


<form action="#" method="POST">

 <input type="text"  name="math" placeholder="math">
 <input type="text" name="physics" placeholder=" physics">
 <input type="text" name="art" placeholder="art">
 
 <button type="submit" name="calavg">calc avg</button>
</form>

<?php
if(isset($_POST["calavg"])){
	$sum=0;
	foreach($_POST as $item){
		if($item !="calavg"){
			$sum +=count($item)-1;
		}
	}
	$avg= $sum /count($_POST)-1;
	printf('AVG IS : %s ' ,round($avg,2) );
}

?>


</body>
Posted
Updated 4-Sep-21 3:44am

1 solution

You never add any values to sum. You need something like:
PHP
<?php
if(isset($_POST["calavg"])){
	$sum=0;
    $tot = 0;
	foreach($_POST as $item){
		if($item !="calavg"){
			$sum += intval($item);
            $tot += 1;
		}
	}
	$avg= $sum / $tot;
	printf('AVG IS : %s ' ,round($avg,2) );
}

?>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900