Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this PHP function update array values?

Why doesn't this work the way I think it should?

I have an array and I'd like to modify one of its values with a function.

I've been reading and following some tutorials and think it has to do with the variable scope? Or maybe this is just not the way to approach something like this and should use other methods?

<?php
$someArray = array("value1"=> 0, "value2" => 0);
function test ($a) {
    if ( 5 > 4 ) {
        $a["value1"] += 1;
        echo $a["value1"] . "<br/>";
    }
}
test($someArray);
echo $someArray["value1"];
?>

I don't get why it works when I echo inside the function to get the new value of "value1", but outside it doesn't work.

like image 351
keloteb Avatar asked Jul 14 '26 08:07

keloteb


1 Answers

You are passing as a copy of the array. You should pass the array using the address to reflect the changes done inside the array. Use & (passing as reference):

$someArray = array("value1"=> 0, "value2" => 0);
function test (&$a) {   //Use & here
               ^
    if ( 5 > 4 ) {
        $a["value1"] += 1;
        echo $a["value1"] . "<br/>";            
    }
}
test($someArray);
echo $someArray["value1"];

Here is the Explanation: (fetched from here)

explanation

Read this SO question too.


Other way is to return the value from function. Inside the function, use return and capture it outside:

$someArray = array("value1"=> 0, "value2" => 0);
function test ($a) {
    if ( 5 > 4 ) {
        $a["value1"] += 1;
        echo $a["value1"] . "<br/>";            
    }
    return $a; //Return here
}
$someArray = test($someArray);  //Capture here
echo $someArray["value1"];
like image 72
Thamilhan Avatar answered Jul 20 '26 21:07

Thamilhan