12

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

Roman
  • 124,451
  • 167
  • 349
  • 456

3 Answers3

22

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);
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
  • I think it is exactly what was asking for. Some people say that $_SESSION is a "special" array (because it is global). Does it mean that I should treat it differently (for example I should not pass it by reference. Moreover, I do not need to pass it as an argument)? – Roman Jul 06 '11 at 13:42
  • 1
    they rights its global and you dont need to pass it, but i want to learn u how to Passing by Reference in php – Haim Evgi Jul 06 '11 at 13:45
  • 1
    Thanks a lot! It is cool that you could get what I need from my very short original question. Thanks. – Roman Jul 06 '11 at 13:47
0

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.

Knowledge Craving
  • 7,955
  • 13
  • 49
  • 92
  • As I mentioned in the original post, I would like to have a function because the sequence of calculations needed to generate a new value is big (so, I would like to put everything in a function). – Roman Jul 06 '11 at 13:40
-1
function change_array() {

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

}
Kareem
  • 5,068
  • 44
  • 38