2

I believe this is a long shot, but consider the following:

public function options(array $options = ['route' => '', 'placeholder' => '']) {}

Could I invoke this method such as:

options(['route' => 'search'])

And maintain placeholder as 'placeholder' => ''

Is there anything that could merge the original $options array with the new one?

0

2 Answers 2

6

You could maintain an array of default options and then merge them with the supplied function parameters.

function options(array $options = []) 
{
    $defaults = ['route' => '', 'placeholder' => ''];
    $options = array_merge($defaults, $options);
    // ...
}

options(['route' => 'search']);

Now, all the following would work:

options(['route' => 'search']);
options(['route' => 'search', 'placeholder' => 1]);
options();

Output:

array(2) {
  ["route"]=>
  string(6) "search"
  ["placeholder"]=>
  string(0) ""
}

array(2) {
  ["route"]=>
  string(6) "search"
  ["placeholder"]=>
  int(1)
}

array(2) {
  ["route"]=>
  string(0) ""
  ["placeholder"]=>
  string(0) ""
}
Sign up to request clarification or add additional context in comments.

Comments

0

The answer by Amal Murali is also correct, but, in the place of array_merge() one should consider using array_merge_recursive() so that default options are not overwritten by the options passed when calling the function.

For example:

function getQuiz(array $options) {

  $default = array(
      'conditions' => array(
      'deleted' => 0
    )
  );

 $options = array_merge_recursive(
   $default, 
   $options
  );

  print_r($options);
}

and then calling it like:

$options = array(
  'conditions' => array(
    'id'=>1
  )
);

getQuiz( $options );

Doing a print_r( $options ) inside getQuiz() would give:

array(
  conditions' => array(
    'id' => '3',
    'deleted' => 1
  )
)

1 Comment

Important note here is this is meant for multidimensional arrays, no use for 1-dimensional arrays :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.