0

I can't figure out what the difference is between the final result of $arrayParams in this snippet of PHP.

The function takes string $types, and another parameter called $params. $params itself can be a single value of any type, or an array of values of any type.

The purpose of this code is for binding to call_user_func_array() later on in the code.

The final $arrayParams variable needs to be an array with index 0 as the original $types string, and then the following indices are to be references of the string(s) passed in as $params.

if(is_array($params)) {
  // Make a new array, first index is $types string.
  $arrayParams = array($types);

  // Loop over $params array and add the pointer of each index to $arrayParams.
  // ??? This doesn't seem to be working ???
  foreach($params as $p) {
    $arrayParams[] = &$p;
  }
 }
else {
  // This works fine here, very simple.
  $arrayParams = array($types, &$params);
}

The var_dump of $array_params, when passing $params as an array shows all keys after the first to be a pointer to the same value (?)

1 Answer 1

2
// ...
foreach($params as &$p) {
    $arrayParams[] = &$p;
}
unset($p);
// ...

foreach operates on a copy of the $params-array, unless you specify to use references on the iteration.

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

3 Comments

Can I ask why $p needs to be unset?
@Greg See the warning here.
Accepted answer because of unset tip. Thanks :)

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.