quickshiftin quickshiftin - 1 year ago 78
PHP Question

Bogus PHP (int) typecast behavior?

I've just wasted 3 hours of my life because of Magento's use of an

typecast in PHP. To be fair, the typecast is more than fair on their part... It seems to be unexpected behavior by the interpreter which ruined my afternoon.

$sString = '123 Sesame Street';
$iNumber = (int)$sString;
var_dump($iNumber); // int(123)

Is this intentional? Obviously it can be caught with an
check up-front, but really?

Answer Source

What do you expect the result to be? the (int) works exactly as intended.

If you care to read the PHP manual documentation it states:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Emphesis mine

And because this is such a fundamental realisation of the PHP Type Juggling, I would suspect the issue lies less with Magento's type handling and more with your own interpretion of their type handling abilities. There will be better Magento methods you can employ for a more accurate response.

I would suggest the following pseudo code as a work around for your issue:

if((int)$sString == (string)$sString) {
   //This string is a number and only a number.