开发者

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 ($t开发者_如何转开发est);
}

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.


You need to have you function use the global keyword:

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


While you could easily (and lazily) use the global keyword to make it work, it is a highly discouraged practice (search Stack Overflow to find out why).

Instead, you should have your function accept an array as argument and return a modified array as result:

$test = array("a","b");

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

$test = myTest($test);
print_r($test);

Would render:

Array (
   [0] => c
   [1] => b
)

Alternatively, you can accept the array as reference and work on it directly (without having to return and re-assign):

$test = array("a","b");

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

myTest($test);
print_r($test);

The output would be the same in both examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜