macattack Posted April 22, 2008 Share Posted April 22, 2008 I have created a simple function (the work can be done without a function, I'm just exploring how they work). I can't get the function to work for add and subtract, only for multiply and divide. The add and subtract answers only echo the answer, not the equation. Here is the code, with the form, which I assume works since most of the PHP code works. Use this to magically do algebra!<br> <form action="learn.php" method="post"> <label for="var1">Variable 1</label><input type="text" name="var1"><br> <label for="var2">Variable 2</label><input type="text" name="var2"><br> <select name="operator"> <option>add</option> <option>subtract</option> <option>multiply</option> <option>divide</option> </select><br> <input type="submit" value="Perform selected operation"><br> </form> <br> <?php $var1=$_POST["var1"]; $var2=$_POST["var2"]; $operator=$_POST["operator" ]; function add($var1,$var2) { echo $var1." + ".$var2." = ". $var1 + $var2 . "<br>"; } function subtract($var1,$var2) { echo $var1." - ".$var2." = ". $var1 - $var2 . "<br>"; } function multiply($var1,$var2) { echo $var1." x ".$var2." = ". $var1 * $var2 . "<br>"; } function divide($var1,$var2) { echo $var1." ÷ ".$var2." = ". $var1 / $var2 . "<br>"; } if ($var1 >= 0) { if ($var2 >= 0) { switch ($operator) { case "add": echo add($var1,$var2); break; case "subtract": echo subtract($var1,$var2); break; case "multiply": echo multiply($var1,$var2); break; case "divide": echo divide($var1,$var2); break; } } else { echo "Error.<br>"; } } else { echo "Error.<br>"; } ?> (edited by kenrbnsn to change the tags to ) Link to comment https://forums.phpfreaks.com/topic/102360-solved-function-problem/ Share on other sites More sharing options...
kenrbnsn Posted April 22, 2008 Share Posted April 22, 2008 You don't want to use "echo" in the function, you want to return the value computed: <?php function add ($v1, $v2) { return($v1 + $v2); } function subtract($v1, $v2) { return($v1 - $v2); } function multiply($v1, $v2) { return($v1 * $v2); } function divide($v1, $v2) { return($v1 / $v2); } ?> Ken Link to comment https://forums.phpfreaks.com/topic/102360-solved-function-problem/#findComment-524127 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.