Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug in PHP? [duplicate]

Tags:

php

Possible Duplicate:
php array behaving strangely with key value 07 & 08

I've found something weird in PHP, if I use numeric arrays the 8th array gets ignored, here when I put 'Cherry' into $fruit[08], php seams to step over it.

What's going on ? Is this a bug or something else.

<pre>
<?php

$fruit[01] = "Apples";
$fruit[02] = "Pears";
$fruit[03] = "Bananas";
$fruit[04] = "Grape";
$fruit[05] = "Orange";
$fruit[06] = "Peach";
$fruit[07] = "Lemon";
$fruit[08] = "Cherry";
$fruit[09] = "Mango";

print_r($fruit);

?>
</pre>

Output:

Array
(
    [1] => Apples
    [2] => Pears
    [3] => Bananas
    [4] => Grape
    [5] => Orange
    [6] => Peach
    [7] => Lemon
    [0] => Mango
)
like image 638
AlanW Avatar asked Mar 19 '26 04:03

AlanW


2 Answers

Your indices are being treated as octal numbers because of the leading zeroes.

08 and 09 will both be evaluated as zero, so your last entry ("Mango") ends up in array index 0.

like image 54
Alnitak Avatar answered Mar 21 '26 20:03

Alnitak


08 is treated as octal.

Don't use leading zeros.

For that matter, don't use explicit indices for creating arrays:

$fruit = array(
           "Apples",
           "Pears",
           etc
         );

(or for PHP 5.4 and newer):

$fruit = [
           "Apples",
           "Pears",
           etc
         ];
like image 30
Quentin Avatar answered Mar 21 '26 21:03

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!