如何在 PHP 中编写一个修改数组的函数? [英] How can I write in PHP a function that modifies an array?

查看:23
本文介绍了如何在 PHP 中编写一个修改数组的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个函数,它将数组作为输入并更改数组的某些值(在我的情况下,数组是 $_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).

我该怎么做?

添加

这听起来微不足道.但事实并非如此.我只想为数组设置某些值.例如,我希望我的函数更改 $_SESSION['x'] 和 $_SESSION['y'].据我所知,如果我将数组作为参数传递,则参数的任何更改都不会修改原始数组.例如:

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);

它不会改变 $x.

添加了 2 个

为什么我的问题被否决了?我认为这个问题并不是那么简单,尽管它很短.我还认为我提供了所有相关的细节.据我所知(感谢一个答案)它是关于传递参考".而且,我想修改 $_SEESION 数组的事实使它有点不同.

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

很简单

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

你可以这样称呼它:

changearray($_SESSION);

这篇关于如何在 PHP 中编写一个修改数组的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆