当我连接它时,为什么我的代码会返回错误的总和?

时间:2014-10-10 02:56:44

标签: php

无法弄清楚为什么我的代码在与标签标签连接时不会正确返回总和。 但如果在单独的回声中它可以正确地生成总和

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';
        }

    }

2 个答案:

答案 0 :(得分:1)

将括号()内的变量求和。试试这个..

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

答案 1 :(得分: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 - &gt;整数转换为字符串,然后与其他字符串连接 - &gt; '<label id="sumLabel"> sum = 1'
  2. '<label id="sumLabel"> sum = 1' + 2 - &gt;字符串转换为整数(给出0)并与其他整数求和 - &gt; 2
  3. 2 . '</label>' - &gt;像第一个一样,整数转换为字符串,然后与其他字符串连接 - &gt; '2</label>'
  4. 为避免这种情况,您可以添加括号。

    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

相关问题