NYCPHP Meetup

NYPHP.org

[nycphp-talk] Extracting an int from a query string.

Jake McGraw jmcgraw1 at gmail.com
Tue Nov 13 11:44:02 EST 2007


Perhaps something like:

function ForceInt($input,$default=null) {
  if (is_null($input)||!is_numeric($input)) {
    return $default;
  }
  return intval($input);
}

would work for you? This way you can specify what the default should
be for unexpected or missing input.

If you keep changing how you process input you're eventually going to
get bit by the "I did everything the same here, why doesn't it work?!"
bug. Where ever you can, write a function.

- jake

On Nov 13, 2007 10:57 AM, John Campbell <jcampbell1 at gmail.com> wrote:
> On Nov 13, 2007 9:59 AM, Brian D. <brian at realm3.com> wrote:
> > http://us.php.net/intval
> >
> > You can use:
> > $page_index = intval($_GET['page']);
> >
> > Returns 0 if it's not a valid integer.
> >
>
> I used to do that, but it becomes impossible to distinguish between 0
> and null.  Which is okay until you inherit a database with zeros as
> keys.
> Maybe:
> $page_index = isset($_GET['page']) ? intval($_GET['page']) : null;
>
> This is will not produce any strict errors, but if page='hello' then
> $page_index is 0.  I would rather it be null in that case.
>
> If php's '||' operator wasn't so stupid, we could use constructs like:
> $page_index = intval($_GET['page']) || null;
>
> Auto casting with || and && is on my top 10 list of things I hate about php.
>
> -john campbell
>
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
>



More information about the talk mailing list