开发者

How can I write in PHP a function that modifies an array?

I would like to have a function that takes an array as input and changes some values of the array (in my case the array is $_SESSION but I think it does not really maters).

How can I do that?


ADDED

It sounds trivial. But it is not. I just want to set certain values to the array. For example, I want my function to change $_SESSION['x'] and $_SESSION['y']. As far as I know, if i pass a开发者_运维百科n array as an argument, then any changes of the argument will not modify the original array. For example:

function change_array($x) {
   $x[0] = 100;
}
$x = array(1,2,3);
change_array($x);

It will not change the $x.


ADDED 2

Why my question is down-voted? I think that the question is not so trivial in spite on the fact that it is short. I also think that I gave all relevant detail. As far as I realized (thanks to one answer) it is about "passing a reference". Moreover, the fact that I want to modify $_SEESION array makes it is a bit different.


what you mean its call : Passing by Reference

its very simple like

function changearray(&$arr){
     $arr['x'] = 'y';
}

you can call this like :

changearray($_SESSION);


The coding is like:-

$_SESSION['index_1'] = 'value 1';
$_SESSION['index_2'] = 'value 2';

If you want to change the value for the index "index_2" to value "value 2 changed", then you just simply write:-

$_SESSION['index_2'] = 'value 2 changed'; 

Hope it helps.


function change_array() {

     global $x; /*this will tell the function to work on the array 'x' out of the function itself.*/
     $x[0] = 100;

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜