I have an array for months
$months[01] = 'January';
$months[02] = 'February';
$months[03] = 'March';
$months[04] = 'April';
$months[05] = 'May';
$months[06] = 'June';
$months[07] = 'July';
$months[08] = 'August';
$months[09] = 'September';
$months[10] = 'October';
$months[11] = 'November';
$months[12] = 'December';
Now the array does not output correct value for key 07
& 0开发者_如何转开发8
.
Try doing print_r($months)
you will not get any key value August
and zero key index for September
.
Though I’m able to solve the problem by removing the leading zero, still I would love to know the reason for same.
Even the PHP editor spots some problem but unable to tell what is the problem.
Thanks
Prepending 0 before a number means PHP parses it as an octal value in the same way that prepending 0x causes it to be parsed as a hexadecimal value. Remove the zero, and it will work fine.
echo 07; // prints 7
echo 010; // prints 8
This is mostly used when specifying unix permissions:
chmod("myfile", 0660);
Except for that it's rarely something that you'd want to do.
This is described in the PHP Manual.
Generally, putting a leading 0 on a number tells the compiler that you've giving an octal number (base 8, not base 10).
In octal, 8 and 9 don't exist (8 is 010, 9 is 011), so you're confusing php.
If you really want a leading zero, you can use strings for your indexes
PHP will treat numbers with a leading 0 as octal numbers, either drop the leading 0 or put the key values in quotes.
The way you form an integer literal is important.
See the structure for decimal literals? Notice how a preceeding zero is not part of that pattern?
Either you have to remove the zeros, or treat your array keys as strings
$months['01'] = 'January';
$months['02'] = 'February';
// etc...
I just realized this after precious minutes of debugging and table head banging.
The problem is that PHP doesn't raise an error or even a warning about having malformed the octal literal integer. It just ignores the part from the error until the end of the literal.
Damn.
PS: Who uses octal numbers? never did, never heard of someone using them for a good reason.
Hexadecimal is great, but octal? damn.
Even for permission I usually do chmod ugo+rwx
is more straightforward.
精彩评论