2014-10-10 32 views
0

无法弄清楚为什么我的代码不会正确地返回总和,如果它与标签标签连接。 但它可以正常,如果在不同的回声为什么我的代码在连接时会返回错误的总和?

if(isset($_POST['add'])){ 
     if(!empty($_POST['num1'])&&!empty($_POST['num2'])) 
     { 
      $a = $_POST['num1']; 
      $b = $_POST['num2']; 

      //this works 
      echo '<label id="sumLabel"> sum = '; 
      echo $a+$b; 
      echo '</label>'; 

      //this doesnt work 
      //why wont this code display num of a and b? 
      //instead it returns just value of b 
      //isnt my code above just the same as this? 
      echo '<label id="sumLabel"> sum = ' . $a+$b . '</label>'; 
     } 
     else { 
      echo 'PLEASE INPUT num1 num2'; 
     } 

    } 

回答

1

因为连接和和具有相同的优先级。他们也被关联。

所以操作执行的顺序:

$a = 1; 
$b = 2; 
echo ((('<label id="sumLabel"> sum = ' . $a) + $b) . '</label>'); 
// results 
// first concatenation     ^'<label id="sumLabel"> sum = 1' 
// summing         ^2 
// second concatenation, final result   ^'2</label>' 

让我们来探讨它。

  1. '<label id="sumLabel"> sum = ' . 1 - >整数转换为字符串,然后与其他字符串串接 - >'<label id="sumLabel"> sum = 1'
  2. '<label id="sumLabel"> sum = 1' + 2 - >字符串转换为整数(0给出),并与其他整数总和 - > 2
  3. 2 . '</label>' - >像第一个一样,整数转换为字符串,然后与其他字符串连接 - >'2</label>'

要避免这种情况,您可以添加括号。

echo '<label id="sumLabel"> sum = ' . ($a+$b) . '</label>'; 

http://php.net/manual/en/language.operators.precedence.php

http://php.net/manual/en/language.types.type-juggling.php

+0

@JericRodrigoTibayan,检查'concatenation'单词拼写。并阅读更新的答案。 %) – sectus 2014-10-10 05:38:41

+0

谢谢仙人掌。现在我明白这是为什么它不能正常工作。伟大的链接btw ..非常感谢 – 2014-10-10 05:39:45

1

总和在括号内()变量产生总和。试试这个..

echo '<label id="sumLabel"> sum = ' . ($a+$b) . '</label>'; 
相关问题