1

I want to find the Unique values by username:

so the resulting array would be [0] =>JakeP, [1]=>TomC

My code currently works, but I was wondering is there a better way to accomplish this task with less loops, or using array_unique function?

  Array
    (
        [0] => Array
            (
                [ID] => 3
                [Username] => TomC
                [Project_Name] => Inventory
            )

        [1] => Array
            (
                [ID] => 4
                [Username] => JakeP
                [Project_Name] => Inventory
            )

        [2] => Array
            (
                [ID] => 2
                [Username] => TomC
                [Project_Name] => Stocks

            )

        [3] => Array
            (
                [ID] => 1
                [Username] => Tomc
                [Project_Name] => Stocks
            )

    )

My code which works is :

$names_filter = array();
foreach($latest_projects as $project)
{
if(empty($names_filter)) 
{ 
$names_filter[] = $project['Username']; 
}
else {
foreach($names_filter as $key=>$value)
 { 
 if($value == $project['Username'])
   { break; }
 else
   {
    $names_filter[] = $project['Username'];
   }
  }
}
}

4 Answers 4

3

If you're using PHP >= 5.5 you can take advantage of the array_column() function:

$uniqueNames = array_unique(
    array_column($myArray, 'Username')
);

Prior to PHP 5.5, you can use:

$uniqueNames = array_unique(
    array_map(
        function($value) {
            return $value['Username'];
        },
        $myArray
    )
);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the in_array function to simplify your code. Example:

$names_filter = array();

foreach($latest_projects as $project)
{
    if(!in_array($project['Username'], $names_filter))
    {
        $names_filter[] = $project['Username'];
    }
}

The in_array() function checks for the existence of a value in an array. So the foreach loop will only add a project username to the $names_filter array if it's not in the array. The output should be a list of unique usernames in the $names_filter array.

Comments

2

We can loop through $latest_projects and store each user name to new array ($filter). Since array can't have two elements with same keys, if the key exists it will be overwritten.

$filter = array();
foreach ($latest_projects  as $project) 
{
    $filter[$project['Username']] = 1;    
}

$filter = array_keys($filter);

Comments

2

I can't speak to the performance of this over other solutions, but a similar effect can be achieved with the use of array_map and array_unique. It's not as readable either though, which is just as important.

$uniqueUsers = array_unique(array_map(function ($p) { return $p['Username']; }, $latest_projects));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.