Home > Backend Development > PHP Tutorial > Why Do PHP Arrays with Keys 07 and 08 Exhibit Unexpected Behavior?

Why Do PHP Arrays with Keys 07 and 08 Exhibit Unexpected Behavior?

Susan Sarandon
Release: 2024-10-20 19:34:02
Original
1041 people have browsed it

Why Do PHP Arrays with Keys 07 and 08 Exhibit Unexpected Behavior?

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>
Copy after login

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>
Copy after login

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>
Copy after login

Additional Notes

This behavior is commonly used when specifying UNIX file permissions:

<code class="php">chmod("myfile", 0660);</code>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template