3

I'm new at php/programming and would like to know why this doesn't 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"];
?>

What I don't get is why it works when I echo inside the function to get the new value of "value1", but outside it doesn't work. I'd really appreciate any help/guidance and sorry if this is just too dumb or wrong.

keloteb
  • 33
  • 1
  • 4

4 Answers4

4

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"];
Community
  • 1
  • 1
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
1

Try:

1) return updated array $a from function

2) receive that array in $someArray again

$someArray = array("value1"=> 0, "value2" => 0);
function test ($a) {
    if ( 5 > 4 ) {
        $a["value1"] += 1;
    }
    return $a;
}
$someArray = test($someArray);
echo "Updated ".$someArray["value1"];
Jayesh Chitroda
  • 4,987
  • 13
  • 18
0

Your function echoes stuff but does not alter or return value. What you want to achieve is to change/alter the value, so you can return this value instead of echo in your function and set a variable for that value to echo out. Below, you can find how you should do;

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

And check it here in sandbox

0

Use pass by reference

test(&$someArray); 
shikhar
  • 2,431
  • 2
  • 19
  • 29