ymbyda
Last Updated: February 25, 2016
·
851
· mdotobie

Type Juggling in PHP

I always have to remind myself that PHP does type conversions when comparing operands. I got some really unexpected behavior when iterating through a JSON object using the SPL iterators and searching for a particular key value.

I knew to expect the value to be found twice, but ended up finding it 6 times. Turns out that the iterator was detecting a number of enum arrays and evaluating to true when it encountered the first element of the array. The key value I was searching for was getting converted to an integer when it encountered the 0 key of a normal array and then evaluated to true.

This is the particular citation in the online PHP manual:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

PHP Manual »
Language Reference » Comparison Operators

The Type Juggling page on PHP's Language Reference also sports some additional information about this behavior.

PHP Manual »
Language Reference » Type Juggling