Nov 30, 2008

Even PHP sometimes needs explicit data type conversions

If you're new to PHP, everything seems so easy... When printing, integers automaticly become strings, when parsing user input, strings are automaticly numbers... But sometimes that system fails. You always need to be sure what you're gonna get or use.

It happened to me one day, when writing my Briscola socket server - I was parsing an XML and expecting a number in a node, so I could use it to access a certain index in the array. Of course the array index was numeric, and I had to do a
$my_number += 0;
to it. Which is kinda dumb, but it worked. It fixed the error, and everything went smooth. But that's not really the way to do it,
$my_number = intval($my_number);
is.

No comments: