search

php array change key

May 06, 2023 am 09:01 AM

In PHP, an array is a very powerful data type that can store multiple values ​​and organize them using key-value pairs. Sometimes, during programming, we need to change the keys of an existing array. In this case, we can use some functions provided in PHP to complete this task.

1. Use the array_combine() function

When we need to convert the keys of an array into values, we can use the array_flip() function. Conversely, to convert values ​​into keys, we can use the array_combine() function.

The array_combine() function accepts two arrays as parameters, representing the new key name and the new value respectively. The new key array must be an index array, while the new value array can be an array of any type. If the number of elements in the two arrays is inconsistent, false will be returned.

The following example demonstrates how to use the array_combine() function to change the keys of an array:

// 原始数组
$originalArray = array(
    'name' => 'John',
    'age' => 35,
    'gender' => 'male'
);

// 新键名数组
$newKeysArray = array(
    'person_name',
    'person_age',
    'person_gender'
);

// 使用array_combine()更改键名
$newArray = array_combine($newKeysArray, $originalArray);

// 输出新的数组
var_dump($newArray);

The output is as follows:

array(3) {
  ["person_name"]=>
  string(4) "John"
  ["person_age"]=>
  int(35)
  ["person_gender"]=>
  string(4) "male"
}

In this example, we first define Original array $originalArray. Then, we create a new array $newKeysArray containing the new key names. Finally, we use the array_combine() function to combine the new key names and the values ​​​​of the original array into a new array $newArray.

2. Use the array_map() function

The array_map() function is another very useful function in PHP. It can apply a callback function to all elements in an array. The callback function must accept a parameter that represents the element in the input array. In the callback function, we can process the elements and return the processed results. Finally, the array_map() function returns a new array containing all processed elements.

Note that when using the array_map() function, the keys of the input array will be retained in the output array.

The following is an example that demonstrates how to use the array_map() function to change the keys of an array:

// 原始数组
$originalArray = array(
    'name' => 'John',
    'age' => 35,
    'gender' => 'male'
);

// 使用array_map()更改键名
$newArray = array_map(function($value) {
    $newKey = str_replace('_', ' ', $value);
    $newKey = ucwords($newKey);
    $newKey = str_replace(' ', '', $newKey);
    return $newKey;
}, array_keys($originalArray), array_fill(0, count($originalArray), null));

$newArray = array_combine($newArray, $originalArray);

// 输出新的数组
var_dump($newArray);

In this example, we define an anonymous function that uses the input key name Some string functions return after processing. We use the array_keys() function to get all the keys of the original array, and then use the array_fill() function to generate an array with the same length as the key array, so that we can pass these two arrays to the array_map() function. Finally, we combine the processed key name array and the original array value into a new array, completing the key name change.

3. Use foreach loop

Finally, we can use foreach loop to traverse the original array and create a new array with new key names. During the traversal process, we need to assign the keys and values ​​of the original array to variables $key and $value respectively, and then create a new array item using a new key name $newKey. At the end of the traversal, we get a completely different array in which the key names have been changed.

The following is an example that demonstrates how to use a foreach loop to change the keys of an array:

// 原始数组
$originalArray = array(
    'name' => 'John',
    'age' => 35,
    'gender' => 'male'
);

// 新键名
$newKeys = array(
    'person_name',
    'person_age',
    'person_gender'
);

// 使用foreach循环更改键名
$newArray = array();
foreach($originalArray as $key => $value) {
    $newKey = $newKeys[$key];
    $newArray[$newKey] = $value;
}

// 输出新的数组
var_dump($newArray);

In this example, we first define the original array $originalArray and a new key array$ newKeys. We then use a foreach loop to iterate over the original array. In each loop, we find the corresponding new key name $neKey in the new key name array based on the key $key of the current cycle, and then create a new array item $newArray[$newKey] = $value. After the loop ends, we get a new array $newArray in which the key names have been changed.

The above is the detailed content of php array change key. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.