Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 377
Roman Avatar asked Jul 06 '11 13:07

Roman


1 Answers

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);
like image 55
Haim Evgi Avatar answered Oct 16 '22 07:10

Haim Evgi