Swapping keys and values

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:

    $capitalcities['England'] = 'London';
    $capitalcities['Scotland'] = 'Edinburgh';
    $capitalcities['Wales'] = 'Cardiff';
    $flippedcities = array_flip($capitalcities);

When executed, that will output the following:

array(3) {
    string(7) "England"
    string(8) "Scotland"
    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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Sorting arrays >>

Previous chapter: Using an array as a double-ended queue

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.