Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
If you have an indexed array of objects, and you want to remove duplicates by comparing a specific property in each object, a function like the remove_duplicate_models() one below can be used.
<?php
class Car {
private $model;
public function __construct( $model ) {
$this->model = $model;
}
public function get_model() {
return $this->model;
}
}
$cars = [
new Car('Mustang'),
new Car('F-150'),
new Car('Mustang'),
new Car('Taurus'),
];
function remove_duplicate_models( $cars ) {
$models = array_map( function( $car ) {
return $car->get_model();
}, $cars );
$unique_models = array_unique( $models );
return array_values( array_intersect_key( $cars, $unique_models ) );
}
print_r( remove_duplicate_models( $cars ) );
@amrography

This comment has been minimized.

Copy link

@amrography amrography commented Mar 21, 2020

Saved my day!

Is it necessary to use array_values function on line 29 on php 7+ ?

@kellenmace

This comment has been minimized.

Copy link
Owner Author

@kellenmace kellenmace commented Mar 25, 2020

@amrography Glad to hear it :)

Yes, I would leave in the array_values(). Without that, the array indices of the example above end up being 0, 1, and 3. array_values() serves as a reset for the indices, so if you include it, they end up being 0, 1, and 2.

@amrography

This comment has been minimized.

Copy link

@amrography amrography commented Mar 26, 2020

@kellenmace
Thanks you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.