Array_unique - how-to get first item value in repeated array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mapg
Forum Newbie
Posts: 4
Joined: Mon Aug 28, 2006 7:37 pm

Array_unique - how-to get first item value in repeated array

Post by mapg »

Hi everybody,

I would like to know how-to get the first value of repeated items too in an array using something like array_unique.

With array_unique I get the last one in the list as here ...

Code: Select all

<?php
$array_test = array('111' => 'first one', '111' => 'middle one', '111' => 'last one', '222' => 'first one', '222' => 'last one', '333' => 'first one', '444' => 'first one');

$array_test = array_intersect($array_test, array_unique($array_test));

echo '<pre>';
print_r($array_test);
echo '</pre>';
?>
This will print ...
Array
(
[111] => last one
[222] => last one
[333] => first one
[444] => first one
)
... and I would like to print ...
Array
(
[111] => first one
[222] => first one
[333] => first one
[444] => first one
)
Is there some way to get that array_unique works like that or some other way to remove duplicated items but getting its first value not the last?

Thank you very much in advance. This issue is important for me.

Mapg
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I'm not sure what you've done there but you cannot have the same key multiple times in an array so your code doesn't really make any sense ;)

array_unique() works on the value in the array, not the key since keys are by definition unique.
mapg
Forum Newbie
Posts: 4
Joined: Mon Aug 28, 2006 7:37 pm

Post by mapg »

Thank you for your help

Best,

Mapg
Post Reply