Home >Backend Development >PHP Tutorial >PHP array key-value exchange: a comprehensive analysis from principle to practice

PHP array key-value exchange: a comprehensive analysis from principle to practice

WBOY
WBOYOriginal
2024-05-03 10:21:01520browse

PHP array key-value exchange principle: exchange keys and values ​​to generate a new array. The implementation method is: use the array_flip() function: swap the key values ​​and return a new array. Use the array_combine() function: Create a new array with arrays as keys and values.

PHP 数组键值互换:从原理到实践的全面解析

PHP Array Key Value Interchange: Comprehensive Analysis from Principle to Practice

In PHP, array is a basic A data structure that can be used to store data and access elements by key. Sometimes, we need to interchange the keys and values ​​of the array to meet different needs.

Principle

The principle of array key-value exchange is very simple: store the value of each key as a new value, and store each value as a new key. For example, for the array ['foo' => 'bar', 'baz' => 'qux'], the array after swapping the keys will be ['bar' =&gt ; 'foo', 'qux' => 'baz'].

Syntax

PHP provides a variety of methods to interchange the keys and values ​​of an array. The two most common methods are:

  • array_flip() function: Exchange the keys and values ​​of the array and return a new array. Syntax: array_flip($array)
  • array_combine() Function: Create a new array using one array as the key and another array as the value. Syntax: array_combine($keys, $values)

Practical case

Case 1: Using array_flip() function

Suppose we have an array with user ID as key and username as value:

$users = [
    1 => 'John Doe',
    2 => 'Jane Smith',
    3 => 'Bob Jones',
];

Use the array_flip() function to swap key values, With username as key and user ID as value:

$flippedUsers = array_flip($users);

Now, $flippedUsers will contain the following key-value pairs:

[
    'John Doe' => 1,
    'Jane Smith' => 2,
    'Bob Jones' => 3,
]

Case 2: Using array_combine () Function

Suppose we have two arrays, one containing fruit names and the other containing fruit prices:

$fruits = ['Apple', 'Banana', 'Orange'];
$prices = [10, 15, 20];

Use the array_combine() function to combine the fruits Pair the name with the price, creating a new associative array:

$fruitPrices = array_combine($fruits, $prices);

Now, $fruitPrices will contain the following key-value pairs:

[
    'Apple' => 10,
    'Banana' => 15,
    'Orange' => 20,
]

The above is the detailed content of PHP array key-value exchange: a comprehensive analysis from principle to practice. 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