5.6.7 Swapping keys and values: array_flip()This is NOT the latest copy of this book; click here for the latest version.
array array_flip ( array input)
The array_flip() function takes just one parameter, an array, and exchanges all the keys in that array with their matching values, returning the new, flipped array. You can see how it works in this script:
<?php
$capitalcities['England'] = 'London';
$capitalcities['Scotland'] = 'Edinburgh';
$capitalcities['Wales'] = 'Cardiff';
$flippedcities = array_flip($capitalcities);
var_dump($flippedcities); ?>
When executed, that will output the following:
array(3) {
["London"]=>
string(7) "England"
["Edinburgh"]=>
string(8) "Scotland"
["Cardiff"]=>
string(5) "Wales"
}
As you can see, "London", "Edinburgh", and "Cardiff" are the keys in the array now, with "England", "Scotland", and "Wales" as the values - simple.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|