-
array_flip
Posted on April 19th, 2010 3 commentsThe array_flip() PHP function changes all the keys in an array into values, and all the values into keys.
PHP
$a = array('apple' => 1, 'ibm' => 2, 'sun' => 3); $flipped = array_flip($a); print_r($flipped); /* Array ( [1] => apple [2] => ibm [3] => sun ) */
To replicate this functionality in Ruby, we will use a Hash object, since arrays in Ruby don’t use associative key / value pairs.
Ruby
hash = { "apple" => 1, "ibm" => 2, "sun" => 3 }; flipped = hash.invert; p flipped; # => {1 => "apple", 2 => "ibm", 3 => "sun"}
In PHP, the array_flip() function will over write any conflicting keys. The Ruby invert() method behaves the same - any keys which are the same as other keys will overwrite the previous one.
3 responses to “array_flip”
-
in the first row of ruby code a syntax mistake… but good description!
-
RubyLove July 5th, 2010 at 23:18
Thanks for pointing out the mistake, I have corrected it
-
Jaume Sola July 3rd, 2011 at 21:33
This is what you would do if you want to flip a Ruby array into a Ruby hash:
a = ["apple", "orange", "banana"]
flipped = {}
a.each_with_index { |e, i| flipped[e] = i }p flipped
=> {”apple”=>0, “orange”=>1, “banana”=>2}
Leave a reply
-


