dooode dooode - 3 months ago 12
PHP Question

update a global array within a function

I have a global array in which I am trying to update a value (remain persistent) and then display it.

I get no error but the array never gets updated.

<?php
$anchor = 'bird';
$stuff = array('apple', 'bird', 'frog');

function insert($anchor, $stuff){
foreach($stuff as $part){
$new_array = array($anchor => rand());
if($part == $anchor){
array_push($stuff, $new_array);
}
}
}

for($x = 0; $x < 2; $x++){
insert($anchor, $stuff);
var_dump($stuff);
}


output:

array(3) {
[0]=>
string(5) "apple"
[1]=>
string(4) "bird"
[2]=>
string(4) "frog"
}
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(4) "bird"
[2]=>
string(4) "frog"
}


expected output:


{'bird' => 674568765}

{'bird' => 986266261}


How do I update an array within a function, so that the changes are reflected globally (persistent)?

Answer

Pass the variable $stuff by reference. Note the & in the function parameters.

function insert($anchor, &$stuff){    // note the & mark
        foreach($stuff as $part){
                $new_array = array($anchor => rand());
                if($part == $anchor){
                        array_push($stuff, $new_array);
                }
        }
}