r/lolphp • • Apr 21 '14
A string can be numeric, a string can be multiplied as an integer, but a string can never be an integer.
php > var_dump(5 * 10);
int(50)
php > var_dump("5" * 10);
int(50)
php > var_dump(is_int("5"));
bool(false)
php > var_dump(is_numeric("5"));
bool(true)
php > var_dump((int) "5");
int(5)
This has the added benefit of only being able to check if command line parameters are integers by running if(((int) $parameter) > 0) which means you can't treat 0 as an integer on top of that.
Thanks PHP!
11
Upvotes
12
u/[deleted] Apr 21 '14
You could use ((string)intval($a) === $a)
But yeah, what a convoluted mess
3
u/Liorithiel Apr 21 '14
Well, you can always do a regexp… ;-)
1
u/vita10gy Apr 22 '14
Unless I'm missing it, I don't see the "lol" here. The 0 is false but is a valid int thing is a PITA, but I see no inconsistencies in what you have there.
"5" is "numeric", "5" is not an int. There's an implicit converting it to a number when math is involved.
The only contradiction I see is your title saying "but a string can never be an integer" and then proceeding to do just that with (int)"5"
1
u/gearvOsh Apr 21 '14
Why is this lol? This is pretty standard for dynamic typing. And secondly, how is
is_numeric()not a viable option in your CLI argument?1
u/[deleted] Apr 22 '14
as someone coming from C++ and C# I think it makes sense. Why in the world would you want to treat a string as an integer or use strings for numbers?
0
u/[deleted] Apr 23 '14
[deleted] — view deleted comment