Auto-casting numeric strings to int/float

I recently came across this really helpful PHP trick:

You can cast a numeric string to either int or float, depending on its contents, by simply adding 0:

var_dump("1" + 0);
// int(1)

var_dump("1." + 0);
// float(1)

var_dump("1.0" + 0);
// float(1)

var_dump("1.5" + 0);
// float(1.5)

That's much cleaner than trying to make a conditional cast yourself:

$number = '1.0';
if (strpos($number, '.') === false) {
    $number = (int)$number;
} else {
    $number = (float)$number;
}

Just add 0 and let PHP handle it for you ☺

Try it out with 3v4l: https://3v4l.org/6W9tS

Enjoy this article?

About Colin O'Dell

Colin O'Dell

Colin O'Dell is a Senior Software Engineer at SeatGeek. In addition to being an active member of the PHP League and maintainer of the league/commonmark project, Colin is also a PHP docs contributor, conference speaker, and author of the PHP 7 Migration Guide.