Skip to Main Content
Upgrading to PHP 5
book

Upgrading to PHP 5

by Adam Trachtenberg
July 2004
Intermediate to advanced content levelIntermediate to advanced
350 pages
10h 9m
English
O'Reilly Media, Inc.
Content preview from Upgrading to PHP 5

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert PHP and MySQL®

Expert PHP and MySQL®

Andrew Curioso, Ronald Bradford, Patrick Galbraith
Pro PHP Programming

Pro PHP Programming

Peter MacIntyre, Brian Danchilla, Mladen Gogala
Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596006365Supplemental ContentCatalog PageErrata