PHP Array Anomalies with Keys 07 and 08
Encountering unusual array behavior with keys 07 and 08 in a PHP array defined as follows:
<code class="php">$months[01] = 'January'; $months[02] = 'February';</code>
When attempting to print the array using print_r($months), keys 07 and 08 are missing, and September appears with a key of 0 instead.
Reason and Solution
The irregularity arises because numeric keys starting with 0 are interpreted as octal values in PHP. This means that 07 is parsed as the integer 7, and 08 is parsed as 8. To avoid this problem, simply remove the leading 0s from the keys.
<code class="php">$months[7] = 'July'; $months[8] = 'August';</code>
This will ensure that the keys are properly recognized and the array behaves as expected.
Example
The following code demonstrates the difference between using leading 0s and not:
<code class="php">echo 07; // prints 7 echo 010; // prints 8 echo 7; // prints 7 echo 10; // prints 10</code>
Additional Notes
This behavior is commonly used when specifying UNIX file permissions:
<code class="php">chmod("myfile", 0660);</code>
However, it is rarely necessary for other purposes. The PHP Manual provides further details on numeric keys and octal values.
The above is the detailed content of Why Do PHP Arrays with Keys 07 and 08 Exhibit Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!