@znailz - I don't think that's doing what you describe, per se...
"It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array. "
the array_flip() in fact, overwrites any values that are duplicated as it iterates through the array (however it does that under the hood... not through actual iteration, I assume, based on the speed at which array_flip operates); it doesn't "unset them all"
that's all well and good. The end result is as you describe... But, no good for associative arrays (which you mention... "returns a reindexed array"). To preserve keys, you could simply array_flip($arr) at the end.
just a thought. It's a good solution, but just caught my eye.
array_flip
(PHP 4, PHP 5)
array_flip — 배열 안의 모든 키를 각 키의 연관 값과 교체
설명
array array_flip
( array $trans
)
array_flip()은 뒤집힌 순서의 array를 반환한다. 즉, trans의 키는 값이 되고, trans의 값은 키가 된다.
trans의 값들은 유효한 키가 되어야 한다는 것에 주의한다. 즉, 그 값들은 integer나 string이 될 필요가 있다. 어떤 값이 잘못된 타입을 갖으면 경고메시지가 보일것이다. 그리고 결과적으로 키/값 쌍은 뒤집히지 않을것이다.
같은 값이 여러번 출현하면, 그 값의 제일 마지막 키를 사용할것이고, 나머지 모두 사라지게 될것이다.
인수
- trans
-
뒤집을 키/값 쌍의 배열.
반환값
성공시엔 뒤집은 배열을, 실패시엔 FALSE를 반환합니다.
예제
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
)
jripley at azorus dot com
31-Jan-2012 09:20
kjensen at iaff106 dot com
06-Jan-2012 10:23
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
?>
Final
16-Dec-2011 04:16
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.
h3x
12-Sep-2010 01:11
this function can be used to remove null elements form an array:
<?php
$ar = array(null,'1','2',null,'3',null);
print_r($ar);
/*
result:
Array
(
[0] =>
[1] => 1
[2] => 2
[3] =>
[4] => 3
[5] =>
)
*/
print_r(array_flip(array_flip($ar)));
/*
result:
Array
(
[1] => 1
[2] => 2
[4] => 3
)
*/
?>
Hayley Watson
20-Mar-2009 02: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 12: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 01: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;
}
?>
pinkgothic at gmail dot com
26-Apr-2007 01: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.
snaury at narod dot ru
23-Nov-2004 11: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 02: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:
Array
(
[0] => Array
(
[0] => 11
[1] => 13
)
?>
)
