PHP intval()
-
Take a look at PHP's intval function.
This can be used to parse a string into an int, for example when processing user input. Except if intval fails to parse the value, it returns 0. Meaning it's impossible to tell the difference between a user who typed in "0" which is an acceptable value, and a user who fat-fingered and instead typed nonsense.
I suppose I could switch to regular expressions for input validation, but then I'd have two problems.
I know, PHP is TRWTF, but I'm doing a side project in PHP because PHP/MySQL is the easiest stack for my web host to run, and I figured it's about time I learned this abomination.
Also, apologies for not tending to the Likes thread. Been busy this week and now I have some 700+ posts to catch up on and like.
-
Make sure you use a framework!
-
Determining if it was a number or not is for the is_numeric() function, or other number checking functions.
-
Substring compare first character to '0', obviously.
-
Use
filter_var()
:[pjh@lenovo tmp]$ cat filter_var.php <?php function p($x){ echo "'$x' -> "; var_dump(filter_var($x, FILTER_VALIDATE_INT)); } p ("1"); p ("0"); p (""); p ("-1"); p ("asdf"); p ("0asdf"); ?> [pjh@lenovo tmp]$ php filter_var.php '1' -> int(1) '0' -> int(0) '' -> bool(false) '-1' -> int(-1) 'asdf' -> bool(false) '0asdf' -> bool(false) [pjh@lenovo tmp]$
-
Make sure to use
===
though, as you would with Javascript and ... no other language, since those two are the only ones that are that dumb.
-
Make sure to use === though, as you would with Javascript and ... no other language,
I wouldn't..
if (( actual_val = filter_var($input, FILTER_VALIDATE_INT)) !== false){ /// do something with your zero or other value }
-
Determining if it was a number or not is for the is_numeric() function, or other number checking functions.http://php.net/manual/en/function.is-numeric.php
IsNumeric works on doubles too, and I only wanted ints.
Turns out in the specific case I was working on, 0 was not acceptable input, so it worked out in the end. Still, coming from a .NET background I much prefer bool TryParse(string input, out int value)
-
The hell? Most PHP conversion functions return a boolean
FALSE
on failure. Why the hell does it return 0?Oh, right... PHP, consistency...
-
The hell? Most PHP conversion functions return a boolean FALSE on failure. Why the hell does it return 0?
Because in PHP, 0 == false, to screw with your head.
-
If I'm dealing with user input that's supposed to be numeric, I almost always want non-zero anyway, and in almost every case intval (or even my preferred choice which is just type coercion via (int) as a prefix) will be fine, followed up by a variable > 0 check.
is_numeric has other fun properties like allowing 1.0e5 type notation as well as negative numbers. If in doubt, you can always accept the raw string into $var and compare $var === (string)(int) $var. Ugly but it works.
-
Because in PHP, 0 == false, to screw with your head.
However,
0 !== FALSE
, and I always use===
or!==
when dealing with converted values.(or even my preferred choice which is just type coercion via (int) as a prefix)
I do that as well. Though it will do the same thing, won't it? I didn't have any problems with it either way since I usually just use
is_<type>
before handling anything that might be fishy.Maybe I was bitten by
intval
before and now I avoid it without even realizing it?
-
is_numeric has other fun properties like allowing 1.0e5 type notation as well as negative numbers. If in doubt, you can always accept the raw string into $var and compare $var === (string)(int) $var. Ugly but it works.
I wasn't aware you could cast in PHP. I learned something new this week.
-
I wasn't aware you could cast in PHP. I learned something new this week.
You can even do type hinting in functions:
function someFunction(string someparam) { // do stuff }
It won't enforce the type any further than the original call but hey, at least you can be sure that you passed in the right type.
-
I'm actually having a bizarre problem right now with a value read from a database.
The database value is defined as Decimal for precision. What I have in PHP appears to be a float type since it prints -5.2099999999999996 instead of -5.21. But the weird part is that I was usingabs()
on it for printing purposes and it printed 5.21 >except the documentation for abs() says it will not change the type!!The absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).
So why does abs(-5.2099999999999996) print 5.21?
-
-
Figured it out.. I guess... somehow the database driver for PHP decided I needed to be returned a STRING type for the DECIMAL field, I guess in case that PHP couldn't handle the precision (because it can't if the number had actually been using the full precision of the field in the database). However, instead of giving me back a string that actually equaled to the value in the database, it converted it to FLOAT first, then STRING, defeating the entire point.
-
Rounding?
I did some === vs == comparison on the raw -5.20999999999999996 value as a numeric/float type and found that it was not ===, so I actually had a STRING and not a FLOAT. The abs was then converting it from STRING to NUMERIC and that left me with 5.21
-
5.20999999999999996447286321199499070644378662109375 is the actual number that was stored.
-
Turns out in the specific case I was working on, 0 was not acceptable input, so it worked out in the end. Still, coming from a .NET background I much prefer bool TryParse(string input, out int value)
Sooooooo much better.
Why not use Python in place of PHP, anyways? Both the sites on work on professionally and personally, I've replaced all PHP scripts with Python.
-
-
PHP ... Python Hypertext Processor.
Checks out, let's go with that from now on.
-
PHP ... Python Hypertext Processor.
Checks out, let's go with that from now on.
I thought it was Personal Hell Pit.
-
Didn't know you could write web pages with Python. That's an idea for a future project though, I'm far enough along on this one that I don't want to switch.
I'm finding that PHP really isn't that bad for smaller projects. It's just an inconsistent language that seems to encourage spaghetti code, I'd hate to see something large.
-
It's just an inconsistent language that seems to encourage spaghetti code, I'd hate to see something large.
Yeah, kinda. Though my level of hatred for spaghetti code is great enough for me to go out of my way and fight any notion of it, by anyone. I can't even stand the old
<form action=$_SERVER['PHP_SELF']>
bullshit and eradicate it as soon as I find it.So yeah, it's possible to write good code in PHP (or as close as the language will let you), but it sure makes it easy to build crap.
-
PHP ... Python Hypertext Processor.
Checks out, let's go with that from now on.
That is libelous...
-
Several years ago, a non-profit I was involved with was looking for an assistant webmaster for their PHP-based site. I didn't know PHP, but I volunteered anyway, thinking it would be really easy to learn. One thing I have learned from TDWTF, I am really glad they did not take me up on my offer. They saved me from much trauma.
-
Several years ago, a non-profit I was involved with was looking for an assistant webmaster for their PHP-based site. I didn't know PHP, but I volunteered anyway, thinking it would be really easy to learn. One thing I have learned from TDWTF, I am really glad they did not take me up on my offer. They saved me from much trauma.
If only I knew. Back around 2007, my company had a .NET wrapper for the Authorize .NET API, but we had some clients that preferred PHP. It fell on me to rewrite it in PHP, which I did manage, but did not have fun with. Dealing with it back then is the reason why I don't deal with it now.
Just got an email from a headhunter yesterday about a PHP job, it was pretty easy to immediately turn down.
-
You likely would not have experienced any trauma, and probably would have had a good time.
Now, the person who came in AFTER you...
-
Apropos of fuck all...
There's no i in Brillant
There is. There just isn't two of them.
Filed under... sod it. I could cheat and just award myself a pedantry award anyway...
Edit:
Awarded Pedantic Dickweed of the Most Honourable Order of the Bath:
-
I'd vote for you having a pedantic dickweed award.
-
Flag it then. It'll go through the motions while I still figure out the bookkeeping required for the minimum 625 flags required for gold...
-
Foul!
Implementation details are SECRET! If you must say it, do so <SECRETLY!>
-
625 isn't secret. Bookkeeping them should be: its worthy of a Front Page, given what I have to work with....
-
Because in PHP, 0 == false, to screw with your head.
C does this too...
Edit: Seriously, quoting should be the default and quoting in an edit shouldn't attempt to QUOTE THE POST I'M EDITING. As usual, Discourse is the real WTF.
-
Another example of a coding horror?
-
Glad I could drive at least one person crazy.
-
625 isn't secret. Bookkeeping them should be:
When I originally proposed the pedantic dickweedery badges, it was my intention that moderators use their discretion to award badges based on the level of pedantry of the individual post; no bookkeeping involved. Rather like the UK honours system: It's not (I think) necessary to already have, say, an OBE to be awarded a KG, if you do something sufficiently meritorious.
its worthy of a Front Page
By all means, write it up. It's sure to be better than some of the Front Page articles.
-
Surely bookkeeping such things by hand necessitates a pedantic dickweed badge in itself?
If you have to automate something like that, I'd argue that you've also qualified for the 'missing the joke' badge.
I think I speak for a non-trivial segment of this community in saying that while we appreciate pedantry as a native part of our industry, the fact we're here means we also have a sense of humour and possibly a sense of fair play, where rules don't have to be enforced explicitly and rigidly because we appreciate that in general we have brains.
It's only dickweeds like @codinghorror that feel the need to act as petty jobsworths where the rules must be followed.
-
I fully considered making the post public so people could see the tracking live so to speak.
Yes. Tracking is currently being done in a post on here.
If I haven't either made it public, or made a public copy by Monday, someone remind me by PM...
-
So, who do I nominate for a 'TRWTF award'?
-
t's only dickweeds like @codinghorror that feel the need to act as petty jobsworths where the rules must be followed.
Awww. I can do petty and jobsworth if you want me to... want a snowflake award? ;-)
-
I don't believe I've earned such an award yet. But if you must fulfil your petty, pedantic dickweed jobsworth asshattery quota for the day, by all means.
-
Can he have a different snowflake award? Mine will stop being special otherwise.
-
I suppose a special and unique snowflake does need to be unique otherwise a primary key constraint would be violated. Violently if necessary.
-
Happy now?
-
special and unique snowflake
But it's only special; it doesn't say it has to be unique.
-
In that place that we do not speak about (because the first rule of .... is that we do not talk about ....), it is asserted that special and unique are indeed properties of snowflakes. Or is it 'beautiful and unique'? It's been too long.
-
But it's only special; it doesn't say it has to be unique.
That part is implied by it being a snowflake.
-
625 isn't secret. Bookkeeping them should be: its worthy of a Front Page, given what I have to work with....
Excel?