I need to convert strings to intiger but with distinguish "foo"
from "0"
, because intval()
php function converts non numeric values to 0
.
With inputs:
$a = "10"
$b = "foo"
$c = "0"
$d = "10.5"
I expecting after convertion:
$a == 10
$b == "foo" // or false or whatever that is not an integer
$c == 0
$d == 10.5
You could consider using conditional operator, code would like somehow as below:
$foo = is_numeric($bar) ? (float) $bar : $bar;
There's no reason to overthink that solution, this should be enough.
You could always use is_numeric()
.
if (is_numeric($value)) {
$integer = (int) $value; // Or use intval()
$floatOrInteger = $value + 0; // Can also give a float, so watch it.
} else {
echo "Value is not numeric!";
}
See the code in action here: https://3v4l.org/j4Utb
EDIT
Look at the comments of the documentation I linked if you want more fine-grained control. There's tons of really useful tricks there.
You could use is_int
to test, if it is really an integer. After that, you have to determine, if it's a float. A simple check like (int) $value == (float) $value
could be sufficient in your case.
Wrapping things up in a function could look like this:
function toNumber($value) {
if (is_numeric($value)) {
if ((int)$value != (float)$value) {
return (float) $value;
}
return (int) $value;
}
return $value;
}
The result of your examples (and some others) would be
var_dump(toNumber('10')) . "
";
var_dump(toNumber('foo')) . "
";
var_dump(toNumber('0')) . "
";
var_dump(toNumber(10.5)) . "
";
var_dump(toNumber('-10')) . "
";
var_dump(toNumber('')) . "
";
var_dump(toNumber('10.0')) . "
";
with
int(10)
string(3) "foo"
int(0)
float(10.5)
int(-10)
string(0) ""
int(10)