Posts Tagged ‘array_merge’

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.