Page 1 of 1

array_walk acting weird

Posted: Sun Jun 21, 2009 8:09 pm
by socket1
Array_walk is not doing what it's supposed to do. Or maybe i'm not doing something right, either case have a look at this:

I have the function that is supposed to remove the [ and ] from a string given to it:

Code: Select all

function stripbraces(&$String) {
        return ltrim(trim($String, ']'), '[');
}
and an array that array_walk will apply the function to:

Code: Select all

$Array = array('[test]', '[test2]', '[anothertest]');
when I run array_walk($Array, 'stripbraces'); and then print_r($Array) it is the same as the original array??? I have &$String as the only parameter in the stripbraces function and the & is supposed to make array_walk apply it to the original array since its a reference so I don't know what's going on.

But yet when I do:

Code: Select all

foreach ($Array as $id => $tag) {
    $Array[$id] = stripbraces($tag);
}
and call print_r($Array) it works perfectly fine.

Re: array_walk acting weird

Posted: Sun Jun 21, 2009 8:13 pm
by socket1
Well that's not supposed to happen. I solved the problem
I had to modify the function to this:

Code: Select all

function stripbraces(&$str) {
    $str = ltrim(trim($str, ']'), '[');
    return $str;
}
Shouldn't the original function work as well? If so then this is definitely a glitch.

Re: array_walk acting weird

Posted: Sun Jun 21, 2009 9:06 pm
by requinix
Your original function never modified $String.

Re: array_walk acting weird

Posted: Sun Jun 21, 2009 9:46 pm
by socket1
Ah, gotcha it just returned the values that $String would be after the two functions.