PHP: Why is the answer to this addition 20 and not 22?

后端 未结 3 1746
南旧
南旧 2020-12-21 02:47

Why is the output to this 20, and not 22? Seeing as you\'re adding 10 + 0xA(which is 10 in HEX) + 2.

$a = 010;
$b = 0xA;
$c = 2;

print $a + $b + $c;

Output         


        
相关标签:
3条回答
  • 2020-12-21 03:06

    See the manual for numbers:

    To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

    010 is an octal number (it starts with a 0 which isn't followed by a decimal point), which is 8 in decimal.

    0 讨论(0)
  • 2020-12-21 03:07

    This will solve:

    <?php
    $a = 10;
    $b = 0xA;
    $c = 2;
    
    print $a + $b + $c;
    ?>
    

    The 0 leading for $a was putting is as an Octal value, not decimal one.

    0 讨论(0)
  • 2020-12-21 03:22

    It's correct!

    (Because the first number is octal so if you want it to be interpreted as a decimal you have to remove the first 0) Se:

    $a = 010;  //Octal -> 8
    $b = 0xA;  //Hex   -> 10
    $c = 2;    //Dec   -> 2
    
    print $a + $b + $c;  //20
    

    Output:

    20
    
    0 讨论(0)
提交回复
热议问题