0

Here's the function I'm trying to call on a set of array items:

function do_this_stuff( &$key ) {

    $lookups = array(
        'this' => 'that'
    );

    if (array_key_exists($key, $lookups)) {
        return $lookups[$key];
    } else {
        return ucwords(str_replace("_", " ", $key));
    }
}

And the call to it:

array_walk($data[$set][0], 'do_this_stuff');

If anything in the $lookups array is in the array in param one of array walk, I want to replace its contents. The do_this_stuff function works, but nothing I've tried has resulted in the actual input array values updating.

4
  • 1
    BTW, what does ELI5 refer to? Commented Jan 29, 2014 at 17:51
  • @Barmar: Explain Like I'm Five, probably? Commented Jan 29, 2014 at 17:52
  • Yea, explain like I'm five. Sorry guys, too much Reddit. Commented Jan 29, 2014 at 17:54
  • Downvoted. Hm. I feel like this is a reasonable question, easily overlooked in the docs. I can't be the only one. Commented Jan 29, 2014 at 17:58

1 Answer 1

4

You need to assign the updated value back to $key, not return it.

function do_this_stuff( &$key ) {

    $lookups = array(
        'this' => 'that'
    );

    if (array_key_exists($key, $lookups)) {
        $key = $lookups[$key];
    } else {
        $key = ucwords(str_replace("_", " ", $key));
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, Barmar! That did the trick. Kind of renders this function useless though, no? I'm new to these functional paradigms.
I'm not sure why you say that. If you mean that you could do the same thing with a for or foreach loop, that's true. Sometimes there's more than one way to skin a cat.
If I wanted to use do_this_stuff outside of array_walk, I would want the function to return or echo, rather than just set equal to $key. Seems like something that just hasn't clicked for me.
But the reason it takes the argument as a reference is so that it can modify what it was given, rather than return or echo it. You could split it into two functions: one that returns the replacement, and another that calls the first function and modifies its argument with what it returns.
Ah, that makes sense. Thank you very much for sticking around and explaining!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.