distinct_by

Get unique items from an array based on a property

Definition

array distinct_by(array $input, &key_function)

From an $input array, removes all the objects that have a non-unique value of $key_function. The first unique entry is kept.

Parameters

array $input

Array of objects to check for duplicates.

string $key_function

A key of the objects in the array. Only one object will be preserved with each key value.

Returns

array

Array obtained by removing all duplicate objects by $key_function from the $input array.

Examples

{
  "inputA":[
   {"name":"Bob","id":0},
   {"name":"Ann","id":0},
   {"name":"Joe","id":1},
   {"name":"Xavier","id":1}
  ],
  "inputB":[
    {"name":"Bob","id":null},
    {"name":"Ann","id":0},
    {"name":"Joe"},
    {"name":"Xavier","id":1}
  ]
}
{ 
  a: distinct_by(inputA, &id),
  b: distinct_by(inputB, &id),        // Warning: id not present in some elements
  emptyArray: distinct_by(`[]`, &id),
  null: distinct_by(`null`, &id),
  object: distinct_by(`{}`, &id)      // Error
}
{
  "a":[{"name":"Bob","id":0},{"name":"Joe","id":1}],
  "b":[{"name":"Ann","id":0},{"name":"Xavier","id":1}],
  "emptyArray":[],
  "null":null
}

Remarks

  • A warning is raised if some objects don't have the $key_function key.
  • The objects that don't have the $key_function key, or its value on them is null, are removed from the array.