1

Are arrays in PHP passed by value or by reference? and other answers describe how in PHP one can pass a variable by reference into a function and modify it inside the function.

But I'd like to pass a variable by reference into a function and modify it =after= (outside of) the function call. I've tried to do something like this several times in my PHP life but it doesn't work.

Example:

$arr=['a'=>['b'=>'B']]; // An array inside an array
$inside=[];
GetInsideArray($arr,$inside);
$inside['b']='C';
... (other similar modifications omitted)
// At this point, $inside['b'] is 'C' but $arr['a']['b'] is still 'B'
function GetInsideArray($arr,&$inside)
    {
    $inside=$arr['a'];
    } // GetInsideArray

Is there a simple way to get this to work?

David Spector
  • 1,520
  • 15
  • 21
  • In this case, you are creating a new variable called `$inside`, if you add `print_r($inside);` after the call to `GetInsideArray()`, it will show a new variable with just the one element of the array. – Nigel Ren Mar 08 '20 at 18:54
  • You have to create the array before you pass it either by reference or value :) – RiggsFolly Mar 08 '20 at 18:56
  • In short this `GetInsideArray($arr,$inside);` is passing an array that does not yet exist, at least in the code you show us – RiggsFolly Mar 08 '20 at 19:03
  • I wanted $inside to be created by the function GetInsideArray. I have added the line "$inside=[];" to answer these early comments by giving $inside an initial value. I want that value to be overwritten by the array element "$arr['a']". – David Spector Mar 09 '20 at 21:46

0 Answers0