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.

 

Next chapter: Sorting arrays >>

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

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar