0

This is a simplified version of a very large user-defined function I have...

function validate_promotional_code($code, $params = ["reference" => "code", "input-type" => "single", "delimiter" => ","]) {
  global $node_connection;
  $operator_array = [
    "Free With Purchase",
    "Buy One Get One Free"
  ];
  return $params;
}

I have used this method of passing an associative array with default values into a user-defined function many times. It lets me set default values for my function without having to worry about which variable is where, etc.

Unfortunately, this function returns nothing, where it should return the $params array containing my default values.

Have I made a syntax error? Why is my function not receiving my default values?

1
  • I think your code is right. When I tried it return default value from the function . How you call the function ? Call the function like this print_r (validate_promotional_code("code")); then it will print the array . Commented Oct 7, 2015 at 10:49

1 Answer 1

2

The default $params array will be used by your function – but only if the function call does not contain a $params argument at all.

If there is any value passed for $params, that one will be used instead of your default. PHP does not care that it’s an array and does not merge it. You’ll have to do that on your own:

function validate_promotional_code($code, $params = []) {
    $defaults = ["reference" => "code", "input-type" => "single", "delimiter" => ","];
    $params = array_merge($defaults, $params);

    // ... work with $params ...
}

The array_merge() function will merge the two arrays, while values in the latter one will overwrite values in the first. That’s why we put $defaults as the first argument.

Sign up to request clarification or add additional context in comments.

Comments

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.