Casting int faster than intval in PHP

For years I've been using intval($var) for being sure something is an integer, and sometimes using (int)$var to cast it into an integer, which essentially does the same thing — learn what casting is.

I'm here to tell you that unless you require the second parameter of intval(), which changes the base, then you should be casting instead.

In the case of casting int, it's about 300% or 3 times as fast as using intval(), and if you use it a lot like I do, for example in setting the correct type/checking for SQL queries, then it's time to switch. I know I am.

You can also pile them up if you want, for example:

$var = (int)(bool)$var;

This will change strings of "1" and "0", actual numbers of 1 and 0, boolean values, and null to True and False (Null is always False). Pretty useful if you've got a bit or tinyint(1) for pseudo-bool columns in your database or what have you, clean it up real nice.

It's sort of strange too because in other languages I always cast when available, but for some reason in PHP I got in the habit of using intval(), floatval(), etc.

Available casts:

One thought on “Casting int faster than intval in PHP”

Leave a Reply