O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Treating Strings as Arrays Causes Errors

PHP 5 complains louder than PHP 4 when you treat a string as an array.

Accessing a multidimensional array element causes a fatal error in PHP 5:

$string = 'string';
print $string[0][0];
PHP Fatal error:  Cannot use string offset as an array

You can still access an individual character in a string using array notation, but as of PHP 4, this is deprecated in favor of curly braces ({ }):

$string = 'string';

// valid, but deprecated
for ($i = 0; $i < strlen($string); $i++) {
    print $string[$i];
}

// valid, and preferred
for ($i = 0; $i < strlen($string); $i++) {
    print $string{$i};
}
string
            string

Passing strings to array_merge( ) and other array functions generates a warning in PHP 5:

$string = "string";
$array = array_merge($string, $string);
PHP Warning:  array_merge( ): Argument #1 is not an array
            PHP Warning:  array_merge( ): Argument #2 is not an array

This does not generate any messages in PHP 4.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required