Just a short one today, because I’m really busy (un)fortunately.

You can take out and check each argument at a time:

1
2
3
4
  $search = isset($_GET['search']) ? $_GET['search'] : null;
  $page = isset($_GET['page']) ? $_GET['page'] : 1;
  $limit = isset($_GET['limit']) ? $_GET['limit'] : 15;
  // etc
  $search = isset($_GET['search']) ? $_GET['search'] : null;
  $page = isset($_GET['page']) ? $_GET['page'] : 1;
  $limit = isset($_GET['limit']) ? $_GET['limit'] : 15;
  // etc

But to do it in one go, just do:

1
  $args = $_GET + array('search'=>null, 'page'=>1, 'limit'=>15);
  $args = $_GET + array('search'=>null, 'page'=>1, 'limit'=>15);

Note that in some cases it is important to filter your input, that is not done here.

  9 Responses to “How I PHP: Using defaults for input arguments”

  1. This will obviously only work with single dimensional arrays. I have long begged the core developers to add a function to merge multi dimensional arrays, while preserving the original structure (not like array_merge_recursive(), which useless in every way).

    Also there has been talk about an ifsetor() to make explict handling as you did on your long version less painful. It was never added, but there is a userland hack:
    http://wiki.php.net/rfc/ifsetor#userland_2

    ReplyReply
  2. This is a good way of setting defaults for required vars.

    ReplyReply
  3. some input filter libraries will provide that kind of mechanism, i didn’t realize that you could just add the arrays together, though now I see it, it makes sense.

    ReplyReply
  4. Heh, I was phping for two years but didn’t knew about it!
    That’s a pity I am not using php anymore :)
    Thank you for a good tip!

    ReplyReply
  5. Sweet. I’m pretty new to PHP but that’s a helpful tip even for a newbie such as myself. I’m still getting used to the syntax, so that all in one, one liner code is difficult one the eyes, but still sweet :)

    Papa Johns Coupons

    ReplyReply
  6. great tip.
    Thanks mate.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

   

Questions? Just ask!

About the author

Hi, I'm Arnold Daniels. How nice that you like to know a bit more about little old me :).

I've spend a big part of my life behind a computer (and not playing games). I've learned a lot about databases, programming and system administration especially on. the LAMP stack (Linux, Apache, MySQL & PHP).

Have a look at what I'm working on now!
© 2012 Jasny · web development Suffusion theme by Sayontan Sinha