Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Array passed by reference to a function?

I have this php function that has to perform some processing on a given array:

processArray($arrayToProcess) {

  $arrayToProcess['helloStackOverflow'] = TRUE;
}

Later, the code invokes the following:

$niceArray = array('key' => 'value');
processArray($niceArray);

The key 'helloStackOverflow' isn't available outside the processArray function. I tried calling the following:

processArray(&$niceArray);

Using "&" helps, however it raises some warning:

Deprecated function: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of populateForm_withTextfields()

Tried the & in there, but that just stops the code.

How should I do this?

like image 294
Jem Avatar asked May 07 '12 13:05

Jem


People also ask

Can you pass an array to a function in PHP?

Like normal variables, you can pass an array by reference into a function by taking a reference of the original array, and passing the reference to the function. Here is a PHP script on how to pass array as reference: <?

When an array element is passed to a function it is passed by?

In C function arguments are always passed by value. In case of an array (variable), while passed as a function argument, it decays to the pointer to the first element of the array. The pointer is then passed-by-value, as usual.

Can array be passed by reference?

Like all Java objects, arrays are passed by value ... but the value is the reference to the array. Real passing by reference involves passing the address of a variable so that the variable can be updated. This is NOT what happens when you pass an array in Java.

How arrays can be passed to functions by value reference?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().


2 Answers

You have to define the reference in the function, not in the call to the function.

function processArray(&$arrayToProcess) {
like image 172
xCander Avatar answered Oct 02 '22 01:10

xCander


processArray(&$arrayToProcess) {

  $arrayToProcess['helloStackOverflow'] = TRUE;
}

implements the reference in PHP way.

See http://fi2.php.net/references for useful information about references.

like image 45
Smar Avatar answered Oct 02 '22 01:10

Smar