Weird PHP behavior: won't assign the integer 8 to a variable

后端 未结 5 394
灰色年华
灰色年华 2021-01-28 13:18

I think I just encountered the strangest \'bug\' I\'ve ever encountered in my short developer life. It seems like I just can\'t assign the value eight to any variable. For exemp

相关标签:
5条回答
  • 2021-01-28 13:56

    PHP treats numbers with a preceding 0 as an octal.

    Re: PHP:Integers.

    0 讨论(0)
  • 2021-01-28 14:01

    (s)printf is the only right way to do that.

    0 讨论(0)
  • 2021-01-28 14:05

    if you prefix your numbers with a zero (0) they are interpreted as octal numbers. 7 is the highest octal number. there’s also 0x for hexadecimal numbers (up to 15/F)

    how to fix: just don’t prefix with 0 ;)

    0 讨论(0)
  • 2021-01-28 14:11

    In PHP, a number that's prefaced by a zero is considered to be octal. Because octal (base 8) only has digits 0-7, 08 is invalid and treated as zero.

    See this manual page for more information, and note the warning in the syntax section: "If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored."

    <?php
    var_dump(01090); // 010 octal = 8 decimal
    ?>
    
    0 讨论(0)
  • 2021-01-28 14:15

    If your looking to lead a number with zero (Like a month calendar) you could try something like this:

    <?
       for ($num = 1; $num <= 31; $num++) {
       if($num<10)
          $day = "0$num"; // add the zero
       else
          $day = "$num"; // don't add the zero
       echo "<p>$day</p>";
    ?>
    

    Looks like everyone else also stated that a number leading with zero is treated as Octal

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