您應該按照以下方法進行操作,因爲在if子句中,您的評估應該一直歸結爲真或假。但是您在if和elseif子句中的當前計算沒有這樣做。
<?php
if(isset($_POST["btnSubmit"])){
$a = $_POST["text1"];
// first get the what operator you have
// extract the first number or the numbers left side of the operator
// extract the last number or the numbers right side of the operator
$operator = false;
if (stripos($a, "+")) {
$operator = substr($a, stripos($a, "+"), 1);
$firstNumber = substr($a, 0, stripos($a, "+"));
$lastNumber = substr($a, stripos($a, "+")+1);
} elseif (stripos($a, "-")) {
$operator = substr($a, stripos($a, "-"), 1);
$firstNumber = substr($a, 0, stripos($a, "-"));
$lastNumber = substr($a, stripos($a, "-")+1);
} elseif (stripos($a, "*")) {
$operator = substr($a, stripos($a, "*"), 1);
$firstNumber = substr($a, 0, stripos($a, "*"));
$lastNumber = substr($a, stripos($a, "*")+1);
} elseif (stripos($a, "/")) {
$operator = substr($a, stripos($a, "/"), 1);
$firstNumber = substr($a, 0, stripos($a, "/"));
$lastNumber = substr($a, stripos($a, "/")+1);
}
// make sure that user submited operator is one of the above operators
if ($operator == false)
die("Wrong operator");
if($operator == '+') {
echo ($firstNumber + $lastNumber);
} else if ($operator == '-') {
echo ($firstNumber - $lastNumber);
} else if ($operator == '*') {
echo ($firstNumber * $lastNumber);
} else if ($operator == '/') {
echo ($firstNumber/$lastNumber);
} else {
echo "false";
}
}
substr function documentation
stripos documentation
所以,當人將輸入2.然後,在什麼基礎上它會加/減。而且,至少需要2個數字來執行計算?它背後的想法是什麼? –
從你的想法開始'if($ a + $ a){'should do – Federkun
代碼是各種各樣的錯誤。如果特別煩我。在PHP http://php.net/manual/ro/language.types.boolean.php這些值不會做你期望他們做的。你有更多的閱讀要做。 – TigOldBitties