note 47640 added to function.array-flip
| From: | snaury at narod dot ru | Date: | Tue, 23 Nov 2004 19:21:22 +0000 |
| Subject: | note 47640 added to function.array-flip | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-80938@lists.php.net to get a copy of this message | ||
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. =^_^=
----
Manual Page -- http://www.php.net/manual/en/function.array-flip.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47640
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47640&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47640&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47640&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47640&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47640&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47640&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47640&report=yes
Search -- http://master.php.net/manage/user-notes.php