Pei Pei - 7 months ago 9
PHP Question

Change array value globally using function

for some reason, I need to call a function to change certain value in array.
However, from the code I've written, the value is only changed inside the function, and remain intact globally.
Wonder if I've missed something magical?

<?php
$test=array(0=>"a",1=>"b");

function myTest(){
$test[0]="c";
print_r ($test);
}

myTest();
print_r($test);
?>


Ideally, the output should be,
Array ( [0] => c [1] => b )
Array ( [0] => c [1] => b )

However, from my code, the result is
Array ( [0] => c ) Array ( [0] => a [1] => b )
I failed to change the array value, and lost array[1] as well.

Answer

You need to have you function use the global keyword:

function myTest(){
   global $test;
   $test[0]="c";
   print_r ($test);
}
Comments