Re: array_walk, or array_map, or foreach?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, 20 Oct 2006 16:04:27 +0900, Dave M G wrote:

> PHP List,
> 
> I took a snippet of code right off the php.net site to use trim on all 
> the elements of an array.
> 
> Theoretically, it should test if the element in an array is in turn 
> another array, and break it down to the next level until it gets to a 
> string it can use trim on.
> 
> This is the code:
> 
> public static function trimArray($array)
> {
> if (is_array($array))
> {
> array_walk($array, "trimArray");
> }
> else
> {
> $array = trim($array);
> }
> return $array;
> }
> 
> The function exists inside a static class called "Utility" where I keep 
> all basic utility functions.
> 
> I don't know if it's the fact that it's in a static class that makes a 
> difference, but I've tried the following variations on the line with 
> array_walk() in it:
> 
> array_walk($array, "Utlity::trimArray")
> 
> array_map("Utility::trimArray", $array)
> 
> array_map("trimArray", $array)
> 
> I've even tried accomplishing it with a foreach(), but no matter what I 
> do, it doesn't work.
> 
> As it walks through the array, it seems to trim a copy of the element in 
> the array, trim that, but leave the original array untouched.
> 
> What am I missing here?

'pass-by-reference', as mentioned on the array_walk() doc page. Functions
have their own variable scope. If those words mean nothing to you:
http://www.php.net/manual/en/language.variables.scope.php
http://www.php.net/manual/en/language.references.pass.php

Bottom line: the values get changed within the function, but when the
function ends, the value changes are 'lost'.

Ivo

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux