Re: [PHP] array_walk_recursive pass by reference

2010-08-29 Thread Adam Richardson
On Sun, Aug 29, 2010 at 12:35 AM, kranthi  wrote:

> i have an array
> $parms = array('1' => 'a', 'b' => array(3 => 'test'));
> i want $mail = '1:a 3:test';
>

But you're uppercasing and adding new lines and additional spaces, so I hope
you want (at least, this is what I tested against):

"1: A\n3: Test\n"


>
> array_walk_recursive($parms, function($val, $key, &$mail) {
> $mail .= ucwords($key) . ': '. ucwords($val) . "\n";
> }, &$mail);
>

This worked just as you said.


>
> The above function worked perfectly well
> but i am getting: Call-time pass-by-reference has been deprecated in
> /var/www/html/test.php on line 31
>
> if i change it to
>
> array_walk_recursive($parms, function($val, $key, &$mail) {
>$mail .= ucwords($key) . ': '. ucwords($val) . "\n";
> }, $mail);
>
> i am not getting the error but $mail is not being returned.
>

This failed just as you said.

Note, the function signature does not say userdata is passed by reference.
 So, by the time your function is called, the original reference has already
been lost and your function is getting a reference to a copy (bummer, I
know.)

bool *array_walk_recursive* ( array &$input ,
callback
 $funcname [, mixed 
$userdata ] )


>
> ny solution ?
>
>
For a quick fix, I'd use an object, which is pass by reference by nature:

class StringWrapper {
public $string = '';
}

$mail = new StringWrapper();

array_walk_recursive($parms, function($val, $key, $mail) {
   $mail->string .= ucwords($key) . ': '. ucwords($val) . "\n";
}, $mail);

if ($mail->string == "1: A\n3: Test\n") {
echo 'Yes, this worked';
} else {
echo 'No, not again.';
}

You could also use a static method from a class and forget about passing the
$userdata variable, or use a static variable within the function itself to
maintain state.

That said, I've had several situations where I would have preferred the ease
of passing the userdata argument by reference, so I feel your pain.

Adam

-- 
Nephtali:  PHP web framework that functions beautifully
http://nephtaliproject.com


[PHP] array_walk_recursive pass by reference

2010-08-28 Thread kranthi
i have an array
$parms = array('1' => 'a', 'b' => array(3 => 'test'));
i want $mail = '1:a 3:test';

array_walk_recursive($parms, function($val, $key, &$mail) {
    $mail .= ucwords($key) . ': '. ucwords($val) . "\n";
}, &$mail);

The above function worked perfectly well
but i am getting: Call-time pass-by-reference has been deprecated in
/var/www/html/test.php on line 31

if i change it to

array_walk_recursive($parms, function($val, $key, &$mail) {
$mail .= ucwords($key) . ': '. ucwords($val) . "\n";
}, $mail);

i am not getting the error but $mail is not being returned.

ny solution ?

Regards
KK

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php