murfitUK Posted January 17, 2009 Share Posted January 17, 2009 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) Why? Link to comment Share on other sites More sharing options...
boen_robot Posted January 17, 2009 Share Posted January 17, 2009 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 More sharing options...
murfitUK Posted January 17, 2009 Author Share Posted January 17, 2009 Interesting - I never knew that. Thanks for the explanation. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.