array_walk acting weird

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
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

array_walk acting weird

Post 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.
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

Re: array_walk acting weird

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: array_walk acting weird

Post by requinix »

Your original function never modified $String.
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

Re: array_walk acting weird

Post by socket1 »

Ah, gotcha it just returned the values that $String would be after the two functions.
Post Reply