Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array behaving strangely with key value 07 & 08

Tags:

arrays

php

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 & 08.

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

like image 897
Maanas Royy Avatar asked Jan 20 '11 18:01

Maanas Royy


2 Answers

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.

like image 56
Emil H Avatar answered Sep 28 '22 04:09

Emil H


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

like image 38
Sam Dufel Avatar answered Sep 28 '22 06:09

Sam Dufel