& sign before an array object...why?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mlecho
Forum Commoner
Posts: 53
Joined: Wed Feb 02, 2005 9:59 am

& sign before an array object...why?

Post by mlecho »

hi, i was just reading about the array_walk function...the example states a clever piece:

Code: Select all

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>
what i don't understand is the test_alter function....why must there be an ampersan (&) before $item1, and why is $key present in the parameters...it is not used in the function. I ask all this, as i have applied a similar function, but i want to understand why it works.

thanks
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: & sign before an array object...why?

Post by superdezign »

mlecho wrote:what i don't understand is the test_alter function....why must there be an ampersan (&) before $item1
The ampersand symbolizes the sending of a reference. In PHP, when you send a variable to a function, a copy of that variable is made in the function, not the actual variable itself. The ampersand sends the actual variable (more accurately, the address of the variable in most languages). You only need to use it when you will be actually altering the parameter's data.
mlecho wrote:why is $key present in the parameters...it is not used in the function
Because array_walk invokes the function that way. Did you read the manual? The example shows you that the function is called function($value, $key [,$extraParameters [,...]]) (I think :P).
Post Reply