Roman Roman - 2 months ago 8
PHP Question

How to compare object by properties

I'm trying to compare objects by their properties. I'd like to compare them by their hotelId property. The hotelId is unique for each hotel. For example if I have array of objects like this:

array(4) [
0 => stdClass(5) {
hotelId => 238
hotelName => "Bellevue Dominican Bay" (22)
}
1 => stdClass(5) {
hotelId => 5432
hotelName => "Puerto Plata Village" (20)
}
2 => stdClass(5) {
hotelId => 238
hotelName => "Puerto" (20)
}
]


What I am trying to do is to have unique objects with their hotelId.

My code sofar:

$uniqueHotelObjects = array();
foreach($arrayOfHotelObjects as $hotel){
foreach ($uniqueHotelObjects as $uniqueHotel) {
if($hotel->hotelId !== $uniqueHotel->hotelId){
//??
}
}
}

Answer

If you use the ID as the array key, you only need one loop:

$uniqueHotelObjects = array();
foreach($arrayOfHotelObjects as $hotel){
    // check if the element already exists in the unique array
    if (!array_key_exists($hotel->hotelId, $uniqueHotelObjects) {
        $uniqueHotelObjects[$hotel->hotelId] = $hotel;
    }
}

If you want to keep the last entry instead, you can simply remove the if statement.

Comments