panthro panthro - 3 months ago 7
PHP Question

Array Unique based upon first value only?

My array:

$arr = [['abc', 'a'],['xyz', 'f'],['abc', 'x']];


I need to remove any duplicate first values, eg. there are two abc values, above, array_unique won't work as the second value differs:

$arr = array_unique($arr, SORT_REGULAR);


Is there a way to get only unique values based upon the first value. I cant change the above structure.

The desired output is:

$arr = [['abc', 'a'],['xyz', 'f']];

Answer

array_combine() & array_column() can help. But it would change the order of nested arrays and will hold only last value for duplicates.

$arr = [['abc', 'a'],['xyz', 'f'],['abc', 'x']];
$temp = array_combine(array_column($arr, 0), $arr);

array_column is not available for older versions. (Available in (PHP 5 >= 5.5.0, PHP 7))

Output

array(2) {
  ["abc"]=>
  array(2) {
    [0]=>
    string(3) "abc"
    [1]=>
    string(1) "x"
  }
  ["xyz"]=>
  array(2) {
    [0]=>
    string(3) "xyz"
    [1]=>
    string(1) "f"
  }
}

array_column will return an array with all the values from sub-arrays with 0 index.

array_combine will assign the sub-arrays to the values returned by array_column.

So as same key can not exist twice, it will overwrite the previous values with same key (for 0) with newer values. Thus the new array will hold only the latest (last) value.