|
array_flip
Exchanges all keys with their associated values in an array
(PHP 4, PHP 5)
Example 247. array_flip() example<?php Example 248. array_flip() example : collision<?php
now Array Related Examples ( Source code ) » array_flip Examples ( Source code ) » array_flip Code Examples / Notes » array_flipsnaury
When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array: [1] => 1 [2] => 2 [3] => 3 [4] => 3 [5] => 2 [6] => 1 [7] => 1 [8] => 3 [9] => 3 After flipping will become: (first seen value -> first key) [1] => 7 [2] => 5 [3] => 9 And not anything like this: (last seen value -> last key) [2] => 5 [1] => 7 [3] => 9 In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn't (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that): First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with: $array = array_flip(array_unique($array)); Well, and to achieve that "last comments" effect, just do: $array = array_reverse($array, true); $array = array_flip(array_unique($array)); $array = array_reverse($array, true); In the example from the very beginning array will become: [2] => 5 [1] => 7 [3] => 9 Just what I (and maybe you?) need. =^_^= http://www.callum-macdonald.com/
It might seem obvious, but if you want to remove duplicates from an array, you can use array_flip() twice: $arr = array_flip(array_flip($arr)); benles
In case anyone wants a function that doesn't lose duplicates: function array_invert($arr) { $res = Array(); foreach(array_keys($arr) as $key) { if (!array_key_exists($arr[$key], $res)) $res[$arr[$key]] = Array(); array_push($res[$arr[$key]], $key); } return $res; } pinkgothic
In case anyone is wondering how array_flip() treats empty arrays: <?php print_r(array_flip(array())); ?> results in: Array ( ) I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head's up for the paranoid. eseyarr
In array_unique() user notes, you'll see that the flip flip use is faster than the array_unique() use for that purpose.
rgonzalez
If you need traspose an array (i.e convert columns in rows) for a multidimensional array obtain from a SQL query, try this: That is an array from arrays that represent each columns. Array ( [col1] => Array ( [0] => 10 [1] => 100 [2] => 200 [3] => a ) [col2] => Array ( [0] => 1 [1] => 3 [2] => 2 [3] => 5 ) ) <?php $arreglo_aux = Array(); foreach( $arreglo as $keymaster => $value ) foreach( $value as $key => $elemento ) $arreglo_aux[$key][$keymaster] = $elemento; ?> the results will be Array ( [0] => Array ( [col1] => 10 [col2] => 1 ) [1] => Array ( [col1] => 100 [col2] => 3 ) [2] => Array ( [col1] => 200 [col2] => 2 ) [3] => Array ( [col1] => a [col2] => 5 ) ) Bye. Rodrigo González M. - CHILE znailz
I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array. <?php $arr = array(11,12,13,12); // sample array $arr = array_flip($arr); unset($arr[12]); $arr = array(array_keys($arr)); ?> $arr contains: <?php Array ( [0] => Array ( [0] => 11 [1] => 13 ) ?> ) crescentfreshpot
Furthering benles note, if you don't want duplicate values to overwrite existing keys but need non-duplicate values to be assigned like array_flip, use: <?php function array_invert($arr) { $flipped = array(); foreach(array_keys($arr) as $key) { if(array_key_exists($arr[$key],$flipped)) { $flipped[$arr[$key]] = array_merge((array)$flipped[$arr[$key]], (array)$key); } else { $flipped[$arr[$key]] = $key; } } return $flipped; } $a = array( 'orange' => 'fruit', 'milk' => 'dairy', 'apple' => 'fruit', 'banana' => 'fruit' ); print_r(array_invert($a)); /* Output: Array ( [fruit] => Array ( [0] => orange [1] => apple [2] => banana ) [dairy] => milk ) */ ?> mikeb
Further deriving on benles -> crescentfreshpot, I think the following restatement of array_invert() reads much easier and probably runs faster, too. It does yield the same results: function array_invert($arr) { $flipped = array(); foreach ( $arr as $k => $a ) { # put the value in the key, with a throw-away value. dups are inherently avoided, # though overwritten. not sure if prefixing with if ( !isset($flipped[$a][$k]) ) # would speed this up or slow it down. probably depends on quantity of dups. $flipped[$a][$k] = NULL; } foreach ( $flipped as $k => $fl ) { # now make the keys the values. $flipped[$k] = array_keys($fl); } return $flipped; } anonymous
But array_unique does preserve keys, unlike flip flip
|
Change Languagearray_change_key_case array_chunk array_combine array_count_values array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_diff array_fill_keys array_fill array_filter array_flip array_intersect_assoc array_intersect_key array_intersect_uassoc array_intersect_ukey array_intersect array_key_exists array_keys array_map array_merge_recursive array_merge array_multisort array_pad array_pop array_product array_push array_rand array_reduce array_reverse array_search array_shift array_slice array_splice array_sum array_udiff_assoc array_udiff_uassoc array_udiff array_uintersect_assoc array_uintersect_uassoc array_uintersect array_unique array_unshift array_values array_walk_recursive array_walk array arsort asort compact count current each end extract in_array key krsort ksort list natcasesort natsort next pos prev range reset rsort shuffle sizeof sort uasort uksort usort |