updated Jan 2018
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