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:

<?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 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.