Jump to content

Array - Strange Problem


Recommended Posts

I was messing about with arrays and found something a bit odd. I can't find out if it is a bug or if it supposed to do this. Have a look at this bit of code which builds an array and then prints it out:

<?php$numbers=array (1=>"one",2=>"two",3=>"three",4=>"four",5=>"five",6=>"six",7=>"seven",8=>"eight",9=>"nine",10=>"ten");print "<pre>";print_r ($numbers);print "</pre>";?>

The results is as expected:

Array(	[1] => one	[2] => two	[3] => three	[4] => four	[5] => five	[6] => six	[7] => seven	[8] => eight	[9] => nine	[10] => ten)

But if you leave a leading zero in front of the integers like this:

<?php$numbers=array (01=>"one",02=>"two",03=>"three",04=>"four",05=>"five",06=>"six",07=>"seven",08=>"eight",09=>"nine",10=>"ten");print "<pre>";print_r ($numbers);print "</pre>";?>

the result on screen is this:

Array(	[1] => one	[2] => two	[3] => three	[4] => four	[5] => five	[6] => six	[7] => seven	[0] => nine	[10] => ten)


Link to comment
Share on other sites

It's because when you use a leading zero, the integers get counted as octals. That is, as numbers with a base 8. Just for comparrison, binary digits are numbers with base 2 and decimal digits (the ones that we use on every day basis) have a base 10. So, valid digits in octal numbers are 0, 1, 2, 3, 4, 5, 6 and 7. 8 and 9 are not valid in octals, so PHP fallbacks to "0". Since "nine" comes after "eight", it overwrites it, which is why you don't see an "eight". "10" is the octal equivalent for the decimal "8", but in your case, "10" is a decimal. If you had "010" in place of "08", you'd see "8" in the output and "eight" next to it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...