dooode dooode - 3 months ago 23
PHP Question

update a global array

I have a global array that I am trying to update a key value (remain persistent) and display.
I get no error but my array never gets updated.

code:

<?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 key vaulue within a loop, so that the changes reflect 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);
                }
        }
}
Comments