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?
Support my open-source work via Github or follow me on Twitter for more blog posts and other interesting articles from around the web. I'd also love to hear your thoughts on this post - simply drop a comment below!