Monday, February 3, 2014

Default Parameter Values in PHP Functions

Here's a neat way to set some default parameter values in a PHP function. This only works if a function param is passed in as associative array.

function create_profile($values) {
  if (!is_array($values)) {
    $values = array();
  }
  
  // Default key/values
  $values += array(
      'uid' => NULL,
      'username' => '',
      'mobile' => '99999999',
      'location' => 'POINT(0 0)',
      'fb_id' => ''
  );
}

The most important line is at line 7; where both arrays are merged. If the key/value pair is in the $values array, it will be ignored; else the default values will be used.