-1

I've created this code to initialize and output the elemnts of an associative array using php.

$a=array("first"=>999,"two"=>099);
foreach ($a as $key => $value) {
    echo $a[$key]."<br />";
}

The element with the key first outputs 999 while the other outputs 0. The question is why the 999 which is not stored as string outputs correctly and the 099 dont.. Anyone explaining this? Thanks!

Doen
  • 33
  • 1
  • 1
  • 6
  • 1
    In PHP numbers don't have prepended `0`s. It seems that [PHP7 says "parse error"](https://3v4l.org/HRu5G). You need to either use a string or a proper number ([see](https://3v4l.org/WSEg8)) – kero Feb 12 '16 at 09:30
  • 1
    If you always want this array to have three number values (and to add a leading 0 if it is only 1 or 2 characters long) you can do this: `echo str_pad($a[$key], 3, 0, STR_PAD_LEFT)."
    ";` which will add zeros to the front of the number until the string length is 3.
    – Henders Feb 12 '16 at 09:37
  • 1
    Also, you don't need to do `$a[$key]` if you don't want to. You could just do `echo $value;` instead because the for loop is giving you the `$key` and the `$value` of each array key-value pair. – Henders Feb 12 '16 at 09:43
  • This has nothing to do with arrays: https://3v4l.org/DPB7d – deceze Feb 12 '16 at 10:12

2 Answers2

4

Starting a numeric literal with 0 indicates octal notation. In the octal numeral system (base 8), there's no 9. The number 99 doesn't exist in octal.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

Tack number as strings in array.

$a=array("first" => "999", "two" => "099");
    foreach($a as $key => $value) {
    echo $value."<br />";
    }
sourabh singh
  • 167
  • 1
  • 16