In PHP, we can use the built-in function array_flip() function to reverse the positions of keys and values in the exchange array. The following article will show you how to use the array_flip() function. I hope it will be useful to everyone. help.
PHP array_flip() function
array_flip() function is used to reverse/exchange arrays The key name and the corresponding associated key value, and vice versa. [Video tutorial recommendation:PHP tutorial]
Note: We must remember that the values of the array must be valid keys, that is, they must be integers or strings. If a value is of the wrong type, a warning will be thrown and the associated key/value pair will not be included in the result.
Basic sentence pattern:
array_flip($array);
Parameters:This function only accepts one parameter $array, which is used to specify the key/value pair to be reversed Array to rotate.
Return value:array_flip() function will return the reversed array when the reversal is successful; if the reversal fails, it will return NULL.
How to reverse the keys and values in an array?
The following is a simple code example to see how the array_flip() function reverses the key names and corresponding associated key values in the array.
Example 1:
"php", "1" => "java", "2" => "python", "3" => "mysql"); echo ("反转前:"); var_dump($array); $result=array_flip($array); echo ("反转后:"); var_dump($result); ?>
Output:
Example 2:
"rani", "rishav" => "sristi", "gaurav" => "riya", "laxman" => "rani"); echo ("反转前:"); var_dump($array); $result=array_flip($array); echo ("反转后:"); var_dump($result); ?>
Output:
Note: If the associated key values corresponding to multiple key names are the same, the last key name will be used as its value during conversion, and all others will be lost.
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to reverse the position of keys and values in an array in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!