0

Given a data array ...

$data_array = array (
"old_name_of_item" => "Item One!"
);

... and a rename array ...

$rename_array = array (
"old_name_of_item" => "new_name_of_item"
);

... I would like to produce an output like this:

Array
(
    [new_name_of_item] => Item One!
)

I have written the following function, and while it works fine, I feel like I'm missing some features of PHP.

function rename_keys($array, $rename_array) {
foreach( $array as $original_key => $value) {
    foreach( $rename_array as $key => $replace ) {
        if ($original_key == $key) {
            $array[$replace] = $value;
            unset($array[$original_key]); 
        }
    }
}
return $array;
}

Does PHP offer built-in functions to help with this common problem? Thanks!

2

2 Answers 2

1

You only have to go through the array once:

function rename_keys($array, $rename_array) {
    foreach ( $rename_array as $original_key => $value ) {
        if (isset($array[$original_key])) {
            $array[$rename_array[$original_key]] = $array[$original_key];
            unset($array[$original_key]);
        }
    }
}

This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).

Edit: only replace if a corresponding element exists in $rename_array.

Edit 2: only goes through $rename_array

Sign up to request clarification or add additional context in comments.

7 Comments

You don't need to go through every value in $array, just every value in $rename_array which should be quicker
What do you mean by "correctly"? All keys in the same order, same keys in both arrays?
@James could you post an answer that shows how that would work?
@James, you're right! Martin, replacement keys should be unique. Updated answer to reflect both of these.
Oh, I see, so if there was a duplicate key, it wouldn't get renamed. I think we can deal with that. There shouldn't be duplicate keys. The major improvement in your answer is that, compared to my code, isset() replaces foreach() loop.
|
0

Second time today. This one is easier:

$data_array = array_combine(
        str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);

1 Comment

To answer my own question: this answer is much slower than the my answer. In the worst case (replace all keys), this took 10x longer for 100 elements, 1000X slower for 1000 elements, etc...

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.