Chords
Chords

Reputation: 6858

Using array_walk to alter array values

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.

Upvotes: 0

Views: 1844

Answers (1)

Barmar
Barmar

Reputation: 781058

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));
    }
}

Upvotes: 4

Related Questions