How I PHP: Using defaults for input arguments

by Arnold Daniels on 06/30/2008

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.

Arnold Daniels

I've spend a big part of my life behind a computer, learning about databases (MySQL), programming (PHP) and system administration (Linux). Currently I playing with HTML5, jquery and node.js.

E-mailTwitterLinkedInGithubGittip

There are 9 comments in this article:

  1. 30 June 2008Lukas says:

    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. 30 June 2008Andrew Cairns says:

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

    ReplyReply
  3. 30 June 2008kenrick says:

    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. 7 July 2008Andrew Dashin says:

    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. 21 November 2008Richard says:

    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. 22 February 2010Antje Schipmann says:

    great tip.
    Thanks mate.

Write a comment: