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.
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)

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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With