Bubble Foundry

Typecasting Strings to Integers in PHP

by Peter.

PHP does some funny things when typecasting strings as integers and may not work the way you would expect (to be fair, it is documented). Here are some examples running under PHP 5.2.5 from the Mac OS X command line:

php -r 'var_dump((int) "agbae");'
php -r 'var_dump((int) "zzzzzzzzzzzzzzzzzzzzzzz");'
php -r 'var_dump((int) "2agbae");'
php -r 'var_dump((float) "42165.6agbae");'

This is important to know because PHP allows you refer characters of strings just like you would the elements of an array (and somewhat similar to C’s strings):

php -r '$s = "abcdef"; var_dump($s[2]);'
string(1) "c"

However, giving an invalid key won’t given an error, depending on how your installation of PHP is configured in php.ini. If you give an out-of-bounds string you get an empty string:

php -r '$s = "abcdef"; var_dump($s[45]);'
PHP Notice:  Uninitialized string offset:  45 in Command line code on line 1
string(0) ""

If you give a string key, it is always for the zeroth index, since it is typecasted to an int and typecasting works as described above:

php -r '$s = "abcdef"; var_dump($s['zzzzz']);'
PHP Notice:  Use of undefined constant zzzzz - assumed 'zzzzz' in Command line code on line 1
string(1) "a"