I wrote a script that uses an array that's populated with integer and string data. It worked for some time, but then it began to display incorrect values. I traced the problem to how the integers 8 and 9 are treated by PHP: the array uses 08 and 09 and PHP must be treating such entries as octal, in which 8 and 9 are illegal, and are evaluated as zero. That's what is happening in the script. Here is an illustration of how the script is structured, cut down to the essentials: <?php $test = array( array(10,12,01,'Line 1'), array(10,11,02,'Line 2'), array(10,10,03,'Line 3'), array(10,09,04,'Line 4'), array(10,08,05,'Line 5'), array(10,07,06,'Line 6'), array(10,06,07,'Line 7'), array(10,05,08,'Line 8'), array(10,05,8,'Line 8a'), array(10,04,09,'Line 9'), array(10,04,9,'Line 9a'), array(10,03,10,'Line 10'), array(10,02,11,'Line 11'), array(10,01,12,'Line 12'), array(0,0)); $i = 0; while ($test[$i][0] > 0) { $first = $test[$i][0]; $second = $test[$i][1]; $third = $test[$i][2]; echo '<p>' . $test[$i][3] . ': ' . $first . ', ' . $second . ', ' . $third .'</p>'; $i++; } ?> Code (markup): I included the leading zeros in the array for ease in looking at the values; when they are removed the script works fine. I've tried various ways to try to get PHP to accept 08 and 09 as decimal, but none seem to work. This is a trivial matter, but it is annoying. The array I use is quite large, and I plan to feed data into it that sometimes contains leading zeros, so fixing the display would be easier than fixing the feed, I think. Can someone help? Thanks!
When feeding data into the array, can't you remove the leading zeroes before they are processed into the array?
Yes, but I already have a large array now with leading zeros. Rather than re-do the whole thing, I was looking for a way to simply convert those values with leading zeros so that PHP wouldn't think they were octal.
Use sprintf(); to convert to 1 digit when processing the arrays, then use sprinf(); again to convert to 2 digits for the output. sprintf("%01d", $number); // 1 2 3 ... 9 10 11 sprintf("%02d", $number); // 01 02 03 ... 09 10 11 PHP:
I assume I did it correctly, like this: $second = sprintf("%01d", $test[$i][1]); Code (markup): when reading from the array. This still returns a zero when reading 08 and 09 from the array. Perhaps I didn't understand the suggestion.