Re: shortest possible check: field is set, integer or 0

From: Date: Fri, 02 Dec 2005 09:42:35 +0000
Subject: Re: shortest possible check: field is set, integer or 0
References: 1 2 3 4 5 6 7  Groups: php.general 
Request: Send a blank email to php-general+get-226759@lists.php.net to get a copy of this message
Steve Edberg wrote:
At 5:30 PM +0100 12/1/05, Jochem Maas wrote:
Steve Edberg wrote: Only problem with intval() is that it returns 0 (a valid value) on I knew that. :-)
I figured so, but I thought I'd make it explicit for the mailing list...
failure, so we need to check for 0 first. Adding more secure checks do we? given that FALSE casts to 0.
would make this more than just a one-liner, eg; $_CLEAN['x'] = false; if (isset($_POST['x'])) { if (0 == 1*$_POST['x']) {
I find the 1*_POST['x'] line a bit odd. why do you bother with the '1*' ?
I tend to use that to explicitly cast things to numeric; usually not necessary, but I have occasionally hit situations where something got misinterpreted, so I habitually do the 1*.
      $_CLEAN['x'] = 0;
} else {
      $x = intval($_POST['x']);
      if ($x > 0 && $x == 1*$_POST['x']) {
this is wrong ... if $_POST['x'] is '5.5' this won't fly but is valid according to the OP.
I guess I was interpreting the OP differently; your version is the shortest method I can see to force the input to an integer (but to ensure the non-negative requirement, one should say
    $_CLEAN['x'] = abs(intval(@$_POST['x']));
for some reason I have been assuming that intval() drops the sign - but it doesn't the use of abs() would indeed be required. thanks for that info :-)
). I was adding extra code to indicate an invalid entry as false. And I think that 5.5 would not be considered valid - to quote: "What is the shortest possible check to ensure that a field coming from a form as a text type input is either a positive integer or 0, but that also accepts/converts 1.0 or 5.00 as input?" Although, with more caffeine in my system, doing something like
    $x = abs(intval(@$_POST['x']));
    $_CLEAN['x'] = isset($_POST['x']) ? ($x == $_POST['x'] ? $x : false) : false;
or, to be more obfuscated,
    $_CLEAN['x'] = isset($_POST['x']) ? (($x = abs(intval(@$_POST['x']))) == $_POST['x'] ? $x : false) : false;
should do what I was trying to do, more succinctly.
    - slightly more awake steve
plenty for the OP to chew on anyway ;-)

« previous php.general (#226759) next »