How to change a PHP array’s key

Asked

Viewed 4,175 times

3

I need to change the key of an array

$task=array('Title' => 'Test', 'Description' => 'Description test')

I need to change the key name Description

Is there any way?

I’m working with the Laravel framework

  • 1

    I answered but point out that this is basic PHP.

3 answers

6


It seems simple, but it’s not that trivial.

The answer to your question is: is not possible. That said you would ask me "how is it not possible if the other answers showed how to do it?" and I would answer "they lied (at least omitted) to you".

PHP, by internal decision, decided to define a "generic" structure to work with almost all other data structures, so much so that it is not difficult to read that PHP is oriented to array - almost everything is array in PHP. As well as documentation tail:

A array in PHP is actually an ordered map. A map is a type that relates values to keys. This type is optimized for several different uses: it can be treated as a array, a list (vector), hashtable (which is an implementation of map), dictionary, collection, stack, queue and probably more.

Perhaps I may have overlooked it, but the definition begins with the most important part:

An array in PHP is actually a [...] map that relates values to keys.

And you can’t do it alter a map key. What you can do is copy the value of a key, creating a new one and deleting the old one, but that’s not changing. That’s what the response from Lucas Azambuja made and is the most practical way to get the desired result. You could still abstract this to a function:

function array_replace_key(&$arr, $old, $new, $overwrite = true): bool {
    if (isset($arr[$new]) and !$overwrite) {
        return false;
    }

    $arr[$new] = $arr[$old];
    unset($arr[$old]);

    return true;
}

See functionando on Repl.it | Ideone

To "replace" the key description for descrição, for example, just do array_replace_key($task, 'description', 'descrição'). Case the key descrição already exist in the array it will be overwritten; if this is not the desired behavior, you can pass the last argument as false that the existing value will be kept unchanged, array_replace_key($task, 'description', 'descrição', false). The function will return a boolean indicating whether or not there was a "replacement" of the key.

It is worth remembering that as the value is copied from one key to another, depending on what this value is, you may have problems with memory, because during the execution of the function you will have two identical objects.

The solution with array_merge tends to be bad in most cases, as in addition to keeping 3 copies of your object in memory (one in the original object, another in the function parameter and the third in the new array to be merged), will make an operation that is directly dependent on the size of the array (at least O(N)). This means that if you own a array with thousands of values, the operation will take longer, even if the intention is just to change a key.

As for the solution using functions defined by Laravel I do not know how to evaluate. I don’t know if the functions only do what they promise and how they do it, but initially I think it is unnecessary to use functions of a framework for this. If there are advantages to using them perhaps the Marcos Xavier will be able to respond better.

  • Thank you very much Anderson, your reply was complete and clear, I am starting in WEB programming and it was very good to understand more about this type of manipulation of ARRAY, the explanation about memory was perfect... I had always seen answers giving this same array function, without the slightest explanation, thank you very much.

4

<?php 

$task=array('Title' => 'Test', 'Description' => 'Description test');
$task['NovoNome'] = $task['Description'];
unset($task['Description']);

?>

0

In the Laravel way. I used the contracted syntax of the $array = ['...']; ( available from PHP 5.4 https://secure.php.net/manual/en/language.types.array.php )

$task = ['Title' => 'Test', 'Description' => 'Description test'];

//remove a chave Description,equivalente a unset($task['Description'])
array_forget($task, 'Description');
dump($task);

$task = array_add($task,'New Description','New description test');
//add no início do array
$task = array_prepend($task,'First Key','First');
dump($task);

Up. Tested in Laravel version 5.4 and 5.5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.