简体   繁体   中英

php: the best practice to pass two global arrays to the function to modify them

There are two arrays that need to be changed within a function. How to pass that arrays? The way I know is to declare 2 arrays as global variables within a function:

function myfunc(){
 global $arr1;
 global $arr2;
 //do something
}

Does it make sense and is it possible to pass two arrays as references instead? How (in case if Yes)?

Yes, you can pass the arrays as reference, and that would be preferable to using globals.

function myfunc( array &$arr1, array &$arr2 ) {
    // do something
}

myfunc( $someArray, $someOtherArray );

The & in the function definition tells PHP to pass a reference rather than a value.

Here is how you can pass them by reference, define your function as follows:

function myfunc(&$arr1, &$arr2) {
    // ... modify arrays here
}

Just prepend the function arguments you want passed by reference with an & . Now when they are received by the function, they are references.

You do not have to (and should not) put the & in front of the variables when you are calling the function as this results in a call-time pass-by-reference notice. Just pass them to your function as usual $res = myfunc($first, $second);

See Passing by Reference

I would take another approach (if the arrays are not too big...) to make it clear where the function is called that the original arrays will be changed (although I probably would never changed two global arrays in one function...):

function call:

list($array1, $array2) = myfunc($array1, $array2);

function:

function myfunc($array_x, $array_y){
  //do something
  return array($array_x, $array_y);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM