Home > Enterprise >  Difference of elements in object where key not always available
Difference of elements in object where key not always available

Time:09-23

I have an array ($data['messages']) of objects, and i want to find mileage difference, so on below example it is 5200-5000 = 200 km.

The thing is that the key now always exists. What is the fastest or shortest way, without errors that key do not exist.

Array
(
[0] => stdClass Object
    (
        [speed] => 5
    )
[1] => stdClass Object
    (
        [speed] => 6
        [mileage] => 5000
    )
[2] => stdClass Object
    (
        [speed] => 9
    )
[4] => stdClass Object
    (
        [speed] => 2
        [mileage] => 5200
    ) 
[5] => stdClass Object
    (
        [speed] => 2
    )
)  

So far my solution is:

foreach($data['messages'] as $key=>$value){
    if(isset($value->mileage)) {
        if (@$mileage_min > 0) $mileage_max = $value->mileage; else $mileage_min = $value->mileage;
    }               
}
echo $mileage = round($mileage_max - $mileage_min,1);

...but maybe it is a better and more elegant way to do that.

CodePudding user response:

We can simply put this as:

  • Collect all the mileages.
  • Then, it is just maximum - minimum among them.
  • For set/unset issue of mileage, use null coalescing operator followed by a -1 if it isn't set and strip them using array_filter.

Snippet:

<?php

$mileages = array_filter(array_map(fn($obj) => $obj->mileage ?? -1, $data['messages']), fn($val) => $val >= 0);

echo max($mileages) - min($mileages);

Online Demo

  • Related