我如何在PHP中编写修改数组的函数? [英] How can I write in PHP a function that modifies an array?
问题描述
我想有一个将数组作为输入并更改数组值的函数(在我的例子中,数组是$ _SESSION,但我认为它并不真正)。
我该怎么做?
已添加
听起来微不足道。但事实并非如此。我只是想为数组设置某些值。例如,我想让我的函数改变$ _SESSION ['x']和$ _SESSION ['y']。据我所知,如果我将一个数组作为参数传递,那么参数的任何更改都不会修改原始数组。例如:
function change_array($ x){
$ x [0] = 100;
}
$ x = array(1,2,3);
change_array($ x);
它不会更改$ x。
< hr>
ADDED 2
为什么我的问题被低估?我认为这个问题并不是那么微不足道,尽管它很短。我也认为我提供了所有相关的细节。据我了解(感谢一个答案)它是关于通过参考。此外,我想修改$ _SEESION数组的事实使得它有点不同。
解决方案 函数changearray(& $ arr){
$ arr ['x' ] ='y';
}
你可以这样称呼:
changearray($ _ SESSION);
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.
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);
这篇关于我如何在PHP中编写修改数组的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!