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.


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.