Alex Rivera | Logout

Get unique values from a column in a 2d array

Asked 2011-05-21T18:18:15.803
94

I have a 2d array and need to isolate the unique columns from one column.

$array = [
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 4, ...],
    [..., 'key' => 5, ...],
    [..., 'key' => 6, ...]
];

How do I add elements to the result array only if they aren't in there already? I have the following:

$a = [];
// organize the array
foreach ($array as $k => $v) {
    foreach ($v as $key => $value) {
        if ($key == 'key') {
            $a[] = $value;
        }
    }
}
print_r($a);

Output:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 1
  [4] => 2
  [5] => 3
  [6] => 4
  [7] => 5
  [8] => 6
)

Instead, I want $a to consist of the unique values. (I know I can use array_unique() after looping to get the desired results, but I just want to know of any other ways.)

Edit
Report

1 Answer

17
if (!in_array(...))  
  array_push(..)
answered 2011-05-21T18:20:58.673

Your Answer