PHP Bug by Design

Posted on by

Check the following code snippets. They use square bracket syntax to index data in an array and a string.

$array = array(1,2,3);
print $array[0];
>> 1
print $array['foo'];
>> Notice: Undefined index:  foo

$string = '123';
print $string[0];
>> 1
print $string['foo'];
>> 1

If you access a non existing index in an array you will be notified about a non existing index and NULL is returned. That’s fine so far. But what if you’re doing the same with a string? Is a string an array of characters as you might expect?

Unfortunately not in PHP. A string is a string and accessing a non existing index in a string is a different thing. PHP obviously converts the string index “foo” into an integer since strings have only numerical indices. Casting “foo” into integer is 0 and the character at position 0 is returned – without any notice. A string is not an array of characters.

As you may read here this is also fine for the creators of PHP. For me, I’m sorry, it’s a reason to stop using PHP (if I could at least). Implicit type casts in PHP are a story on its own and notoriously leading to subtle and hard to find bugs. But this one is beyond belief.

The only way to protect you from a catastrophe is to check at any and every usage of arrays if you really have an array. Type hint arrays. Use is_array() excessively. Write thousands of tests.

Better choice – use a well designed programming language. A better supported at least.

4 thoughts on “PHP Bug by Design

  1. Better choice – don’t use functions which are not thought for using it in this way.
    For accessing parts of a string there is substr() – so better avoid those array-like hacks

  2. The problem is not getting a part of a string, but:
    You expect an array and access it with $array[‘foo’] but instead of an array, $array is filled with a string. Normally I would expect an undefined index notice, but this is not thrown, which can lead to unexpected behaviour and nearly untraceable errors.

  3. Pingback: PHP Bug by Design | No Brainer Profits

  4. Btw. its planned in PHP6 to remove the arraystyle access to strings.
    But so or so you could simply add a typehint to the function which expects the array.

    But I aggree this could be hard to track down in an application.

Leave a Reply

Your email address will not be published. Required fields are marked *