What is a better way to get unique array Items based on key in PHP? I'm trying to achieve a set of unique array with my following function.

The Function:



/**
* uniqueAssocArray Removes arrys which have same keys
* @param  Array $array     Array to get unique items from
* @param  String $uniqueKey the unique key 
* @return Array            new array with unique items
* @author Junaid Qadir Baloch &lt;shekhanzai.baloch@gmail.com&gt;
*/

function uniqueAssocArray($array, $uniqueKey) {
  if (!is_array($array)) {
    return array();
  }
  $uniqueKeys = array();
  foreach ($array as $key =&gt; $item) {
    if (!in_array($item[$uniqueKey], $uniqueKeys)) {
      $uniqueKeys[$item[$uniqueKey]] = $item;
    }
  }
  return $uniqueKeys;
}




Example Array:

$actualArray = array(
    user1 =&gt; array(
        'name' =&gt; 'User1',
        'age' =&gt; '25',
        'lastLogin' =&gt; '2013-08-16'
    ),
    user1 =&gt; array(
        'name' =&gt; 'User1',
        'age' =&gt; '25',
        'lastLogin' =&gt; '2013-08-10'
    ),
    user2 =&gt; array(
        'name' =&gt; 'User2',
        'age' =&gt; '35',
        'lastLogin' =&gt; '2013-08-08'
    ),
    user1 =&gt; array(
        'name' =&gt; 'User1',
        'age' =&gt; '25',
        'lastLogin' =&gt; '2013-07-10'
    )
);


I then call the function like so:

$resultArray = uniqueAssocArray($actualArray, 'name');


But...

I wonder is there a better way to do the same ?
Assuming your array is already sorted, you can just overwrite the values every time. Skip the inner if.

function uniqueAssocArray($array, $uniqueKey) {
    if (!is_array($array)) {
        return array();
    }
    $uniqueKeys = array();
    foreach ($array as $key =&gt; $item) {
        $groupBy=$item[$uniqueKey];
        if (isset( $uniqueKeys[$groupBy]))
        {
            //compare $item with $uniqueKeys[$groupBy] and decide if you 
            //want to use the new item
            $replace= ... 
        }
        else
        {
            $replace=true;
        }
        if ($replace) $uniqueKeys[$groupBy] = $item;   
    }
    return $uniqueKeys;
}