4

I'm looking for a nifty php solution to replace a standard forloop. i dont care at all about the inner workings of my normalize method.

Here is my code:

$pairs=[];
foreach($items as $key => $val){
    $key = $this->normalizeKey($key);
    $pairs[$key] = $val;
}

private function normalizeKey($key)
{
    // lowercase string
    $key = strtolower($key);

    // return normalized key
    return $key;
}   

I'd like to learn the PHP language a bit better. I thought array_walk would be nice to use, but that operates on the values and not the keys.

I am looking for a PHP array method that can perform this code instead of a foreach loop.

7
  • Post the normalizeKey method Commented Aug 20, 2016 at 21:35
  • @Mihai done its up Commented Aug 20, 2016 at 21:37
  • 1
    -> array_change_key_case() <- Commented Aug 20, 2016 at 21:37
  • @Rizier123 updated question Commented Aug 20, 2016 at 21:38
  • 1
    Possible duplicate of how to change array keys from uppercase to lowercase? Commented Aug 20, 2016 at 22:39

3 Answers 3

17

You want array_change_key_case

$pairs = array_change_key_case($items);
Sign up to request clarification or add additional context in comments.

Comments

1

Just for fun, though it requires three functions. You can replace strtolower() with whatever since this can already be done with array_change_key_case():

$pairs = array_combine(array_map('strtolower', array_keys($items)), $items);
  • Get the keys from $items
  • Map the array of keys to strtolower()
  • Combine the new keys with $items values

You can also use an anonymous function as the callback if you need something more complex. This will append -something to each key:

$pairs = array_combine(array_map(function ($v) {
                                     return $v . '-something';
                                 },
                       array_keys($items)), $items);

Comments

-2

You can normalise the keys and store them and their corresponding values in a temporary array and assign it to your original $pairs array.

Like so:

$normalised = [];

foreach($pairs as $key => $value) {
    $normalised[$this->normalizeKey($key)] = $value;
};

$pairs = $normalised;

Edit 2022: Or better yet, use @Sherif's answer as it uses a standand library function

4 Comments

The function may be defined as (&$value, $key) but not (&$value, &$key). Even though PHP does not complain/warn, it does not modify the key.
@AbraCadaver I just noticed. It doesn't even throw an error. Thanks! I'll notify the OP
@Sherif It's not undefined behavior, it just does not work the way intended.
Modified answer and it works with any implementation of normalizeKey method

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.