In PHP, I need to write a function that takes a string and returns its conversion to a float whenever possible, otherwise just returns the input string.
I thought this function would work. Obviously the comparison is wrong, but I don't understand why.
function toNumber ($input) {
$num = floatval($input); // Returns O for a string
if ($num == $input) { // Not the right comparison?
return $num;
} else {
return $input;
}
}
echo(gettype(toNumber("1"))); // double
echo(gettype(toNumber("3.14159"))); // double
echo(gettype(toNumber("Coco"))); // double (expected: string)