B.3 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.