downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_intersect_assoc> <array_filter
Last updated: Fri, 13 Nov 2009

view this page in

array_flip

(PHP 4, PHP 5)

array_flipInverte as relações entre chaves e valores

Descrição

array array_flip ( array $trans )

array_flip() retorna um array com com a relação entre suas chaves e valores invertida, ou seja, as chaves de trans passam a ser os valores e os valores de trans passam a ser as chaves.

Note que os valores de trans devem ser chaves válidas, ou seja, eles precisam ser integer ou string. Um aviso será mostrado se um valor é de um tipo inválido para chaves, e o par chave/valor em questão não será invertido.

Se um valor tem várias ocorrências, a última chave será usada como valor, e todos os outros serão perdidos.

Parâmetros

trans

Um array de pares chave/valor para inverter.

Valor Retornado

Retorna o array revertido em sucesso e FALSE em falha.

Exemplos

Exemplo #1 Exemplo de array_flip()

<?php
$trans 
array_flip($trans);
$original strtr($str$trans);
?>

Exemplo #2 Exemplo da array_flip(): colisão

<?php
$trans 
= array("a" => 1"b" => 1"c" => 2);
$trans array_flip($trans);
print_r($trans);
?>

Agora $trans é:

Array
(
    [1] => b
    [2] => c
)

Veja Também



array_intersect_assoc> <array_filter
Last updated: Fri, 13 Nov 2009
 
add a note add a note User Contributed Notes
array_flip
Hayley Watson
20-Mar-2009 10:22
Finding the longest string in an array?

<?php
function longest_string_in_array($array)
{
   
$mapping = array_combine($array, array_map('strlen', $array));
    return
array_keys($mapping, max($mapping));
}
?>

Differences are obvious: returns an array of [i]all[/i] of the longest strings, instead of just picking one arbitrarily. Doesn't do the stripslashing or magic stuff because that's another job for for another function.
dan at aoindustries dot com
07-Mar-2009 08:48
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only retrieve the longest value is unnecessary work.  The following should be O(n) instead of O(n log n).  It could also be:

<?php
function get_longest_value($array) {
   
// Some don't like to initialize, I do
   
$longest = NULL;
   
$longestLen = -1;
    foreach (
$array $value) {
       
$len = strlen($value);
        if(
$len>$longestLen) {
           
$longest = $value;
           
$longestLen = $len;
        }
    }
   
$longest = str_replace("\r\n", "\n", $longest);
    if (
get_magic_quotes_gpc()) { return stripslashes($longest); }
    return
$longest;
}
?>
corz at corz dot org
08-Dec-2008 09:36
<?php
/*
    Fun function to return the longest physical *value* from an array.

    Culled from a small script designed to capture the longest $_POST variable,
    usually the textarea, which would then be dumped to a "emergency post dump file".

    corz at corz dot org
*/

$array = array("input" => "submit", "textarea" => "Some long spiel of text\r\na textarea, probably",
                       
"another-input" => "make me longer", "and" => "another", "etc" => "etc.");

echo
'<!DOCTYPE HTML SYSTEM><html><head><title>long</title></head><body><pre>Longest value: ',
                                           
get_longest_value($array),'</pre></body></html>';

function
get_longest_value($array) {
    foreach (
$array as $key => $value) {
       
$lengths[$key] = strlen($value);
    }
   
asort($lengths);
   
$lengths = array_flip($lengths);
   
$longest = str_replace("\r\n", "\n", $array[array_pop($lengths)]);
    if (
get_magic_quotes_gpc()) { return stripslashes($longest); }
    return
$longest;
}
?>
rdanner
21-Aug-2008 01:17
using array_flip(array_flip($array)) or array_keys(array_flip($array)) as key-collapsing alternatives to array_unique() makes your intention less apparent.  Try:

array_values(array_unique($array))

as a more readable alternative.
Anonymous
29-Feb-2008 07:45
True, array_unique does preserve keys, but if you are incrementing in a loop, then it will stop once the key values break numerical order. If you don't care about preserving keys, a life-saver (originally a headache) for me was...

<?php
$new_array
= array_keys(array_flip($old_array));
?>

i used this little snip-it after results from preg_match_all() as a way to remove duplicates from an array and then re-organize the numerical keys ;)

*Only works on arrays with numerical keys.
Anonymous
31-Oct-2007 06:09
But array_unique does preserve keys, unlike flip flip
eSeYaRr
28-Aug-2007 04:21
In array_unique() user notes, you'll see that the flip flip use is faster than the array_unique() use for that purpose.
Anonymous
08-Aug-2007 08:18
@ callum-macdonald.com:

I guess array_unique() should be used for that.
pinkgothic at gmail dot com
26-Apr-2007 08:37
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.
http://www.callum-macdonald.com/
06-Mar-2007 06:13
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));
mikeb at tracersinfo dot com
06-Feb-2006 10:42
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;
}
crescentfreshpot at yahoo dot com
03-Jul-2005 11:21
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
)
*/
?>
benles at bldigital dot com
06-Mar-2005 01:52
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;
}
snaury at narod dot ru
23-Nov-2004 07:21
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. =^_^=
znailz at yahoo dot com
05-Aug-2003 09:42
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
       
)
?>

)

array_intersect_assoc> <array_filter
Last updated: Fri, 13 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites