Parameter Options Array With Default Values (array_merge).

Posted: June 11, 2010 in PHP5, PHP5.3
Tags: , , ,

When some method or function call can be specified with alternate options using a one dimensional array, for example:

function whoAmI($iam, $baboon, array('setme' => false, 'else' => true));

A lot of programmers tend to manually check the passed option keys and set it’s value, this is what
I see in a lot of tutorials on many PHP sites:

// function or method
function whoAmI($iam, $baboon, array $options = array()) {
  if(count($options) > 0) {
    $options['setme'] = empty($options['setme']) ? 'some_default' : $options['setme'];
    // rest of the key options ..

  // rest of function or method code

Then some programmers comment and say:

The empty is not the correct function to use on set keys. If the value of the key is false, then the return value of empty will also be false, although it should be true. A better solution would be to use the array_key_exists function.

$options[‘setme’] = array_key_exists(‘setme’, $options) ? ‘some_default’ : $options[‘setme’];
// rest of the key options ..

Although the problem with empty on array key/values is correct, the solution is far from better.

Most programmers programming in PHP program in Javascript, and if you know a bit of jQuery or Prototype, you can do the following for default values in arrays.

# jQuery
options = jQuery.extend({
  'setme' : false,
  'else' : false
}, options)

options = Object.extend({
  'setme' : false,
  'else' : false  
}, options);

So can this be achieved in PHP? Of course it can ๐Ÿ˜€

$options = array_merge(array(
  'setme' => false,
  'else' => false,
), $options);

So the function whoAmI would look like this:

function whoAmI($iam, $baboon, array $options = array()) {
   $options = array_merge(array(
     'setme' => false,
     'else' => false
   ), $options);

A simple, elegant solution and yes, a better solution ๐Ÿ˜‰

This can also be used for global variables, for example a $_GET or $_POST values. For example, when you pass the page id as an attribute in your URL:


you can use the following to make sure id has always a default value:

  $_GET = array_merge(array(
    'id' => 1   // default start page
  ), $_GET);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s