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 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' => ; '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($array)
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!