©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5, PHP 7)
array_flip — 交换数组中的键和值
$trans
) array_flip() 返回一个反转后的 array ,例如
trans
中的键名变成了值,而
trans
中的值成了键名。
注意 trans
中的值需要能够作为合法的键名,例如需要是
integer 或者 string 。如果值的类型不对将发出一个警告,并且有问题的键/值对将不会反转。
如果同一个值出现了多次,则最后一个键名将作为它的值,所有其它的都丢失了。
trans
要交换键/值对的数组。
成功时返回交换后的数组,如果失败返回 NULL
。
Example #1 array_flip() 例子
<?php
$trans = array_flip ( $trans );
$original = strtr ( $str , $trans );
?>
Example #2 array_flip() 例子:冲突
<?php
$trans = array( "a" => 1 , "b" => 1 , "c" => 2 );
$trans = array_flip ( $trans );
print_r ( $trans );
?>
现在 $trans 是:
Array ( [1] => b [2] => c )
[#1] Prabhas Gupte [2015-01-27 06:48:22]
array_flip() does not retain the data type of values, when converting them into keys. :(
<?php
$arr = array('one' => '1', 'two' => '2', 'three' => '3');
var_dump($arr);
$arr2 = array_flip($arr);
var_dump($arr2);
?>
This code outputs this:
array(3) {
["one"]=>
string(1) "1"
["two"]=>
string(1) "2"
["three"]=>
string(1) "3"
}
array(3) {
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
string(5) "three"
}
It is valid expectation that string values "1", "2" and "3" would become string keys "1", "2" and "3".
[#2] grimdestripador at hotmail dot com [2014-02-25 00:06:43]
<?php
function array_flip_into_subarray($input){
$output = array();
foreach ($input as $key=>$values){
foreach ($values as $value){
$output[$value][] = $key;
}
}
return $output;
}
[#3] Tony H [2013-04-29 14:59:35]
This function is useful when parsing a CSV file with a heading column, but the columns might vary in order or presence:
<?php
$f = fopen("file.csv", "r");
$cols = array_flip(fgetcsv($f));
while ($line = fgetcsv($f))
{
// Now we can reference CSV columns like so:
$status = $line[$cols['OrderStatus']];
}
?>
I find this better than referencing the numerical array index.
[#4] Anonymous [2012-04-05 10:17:10]
Similarly, if you want the last value without affecting the pointer, you can do:
<?php
$array = array("one","two","three");
echo next($array); // "two"
$last = array_pop(array_keys(array_flip($array)));
echo $last; // "three"
echo current($array); // "two"
?>
[#5] kjensen at iaff106 dot com [2012-01-06 10:23:09]
I needed a way to flip a multidimensional array and came up with this function to accomplish the task. I hope it helps someone else.
<?php
function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) {
$ArrayOut=array();
foreach ($arrayIn as $Key=>$Value)
{
// If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true)
if ($OrigKeyName) $Value[$OrigKeyName]=$Key;
// Require a string value in the data part of the array that is keyed to $DesiredKey
if (!is_string($Value[$DesiredKey])) return false;
// If $DesiredKey2 was specified then assume a multidimensional array is desired and build it
if (is_string($DesiredKey2))
{
// Require a string value in the data part of the array that is keyed to $DesiredKey2
if (!is_string($Value[$DesiredKey2])) return false;
// Build NEW multidimensional array
$ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value;
}
// Build NEW single dimention array
else $ArrayOut[$Value[$DesiredKey]][]=$Value;
}
return $ArrayOut;
}//end multi_array_flip
?>
[#6] Final [2011-12-16 04:16:45]
I find this function vey useful when you have a big array and you want to know if a given value is in the array. in_array in fact becomes quite slow in such a case, but you can flip the big array and then use isset to obtain the same result in a much faster way.
[#7] h3x [2010-09-12 13:11:49]
this function can be used to remove null elements form an array:
<?php
$ar = array(null,'1','2',null,'3',null);
print_r($ar);
print_r(array_flip(array_flip($ar)));
?>
[#8] Hayley Watson [2009-03-20 02:22:10]
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.
[#9] dan at aoindustries dot com [2009-03-07 12:48:42]
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;
}
?>
[#10] corz at corz dot org [2008-12-08 01:36:37]
<?php
$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;
}
?>
[#11] pinkgothic at gmail dot com [2007-04-26 01:37:13]
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.
[#12] snaury at narod dot ru [2004-11-23 11:21:22]
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. =^_^=
[#13] znailz at yahoo dot com [2003-08-05 14:42:06]
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:
Array
(
[0] => Array
(
[0] => 11
[1] => 13
)
?>
)