mapg Posted October 30, 2007 Share Posted October 30, 2007 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 ... <?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 Quote Link to comment https://forums.phpfreaks.com/topic/75345-array_unique-how-to-get-first-item-value-in-repeated-array-item/ Share on other sites More sharing options...
0x00 Posted October 30, 2007 Share Posted October 30, 2007 If you have a box, you can put things in this box, yet when you do the thing that was in it previously gets replaced by the new thing. Therefore every time you tell the associative array that there is a new element to be put in a named position, it replaces it totally. Try this to see what I mean! $array_test = array('111' => 'first one', '111' => 'middle one', '111' => 'last one', '222' => 'first one', '222' => 'last one', '333' => 'first one', '444' => 'first one'); echo $array_test['111']."<br><br>"; while (list($k, $v) = each($array_test)) { echo "".$k.": ".$v."<br>"; } Quote Link to comment https://forums.phpfreaks.com/topic/75345-array_unique-how-to-get-first-item-value-in-repeated-array-item/#findComment-381057 Share on other sites More sharing options...
sasa Posted October 30, 2007 Share Posted October 30, 2007 In your $array_test you don't have multiple value for some key, just last one try <?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'); echo '<pre>'; print_r($array_test); echo '</pre>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/75345-array_unique-how-to-get-first-item-value-in-repeated-array-item/#findComment-381244 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.