Han Timmers
Han Timmers

Reputation: 35

PHP String Indexing 'error'

Without wanting to sollicate the obvious Q&A, I'm wondering if anybody knows why the following happens.

I have a string variable $string with the value '1011100001111'

Testing for a '1' or '0' at a certain position:

$string[00] => '1'  // correct
$string[01] => '0'  // correct
$string[07] => '0'  // correct
$string[08] => '1'  // should be '0'
$string[ 8] => '0'  // correct

It took me a while to find the error when using prefix zeroes, and obviously I got rid of them, but why is index 08 different from 8? Note that up to 07 it does work!

Upvotes: 0

Views: 70

Answers (2)

Matt S
Matt S

Reputation: 15374

From the documentation regarding integers:

To use octal notation, precede the number with a 0 (zero)

So 08 is not the integer 8 and therefore not returning the index you expect. It's an invalid octal and resolves to 0.

Upvotes: 5

aniri
aniri

Reputation: 1831

If you precede the numbers with 0, they will be considered octal numbers. So from 00 to 07, they are equivalent to 0-7 decimal. But 08 does not exist in octal so it resolves to 0.

Upvotes: 0

Related Questions