比较对象集合中的对象类型属性

I have the following $input :

elements: array:2 [
    0 => Tournament { 
        id: 1
        amountStaking: Price { 
            value: 2500
            currency: "EUR"
        }
    }
    1 => Tournament { 
        id: 2
        amountStaking: Price { 
            value: 2500
            currency: "EUR"
        }
    }
]

What I want to achieve is a function that will return an object or false depending of the "equality" of the $amountStaking property of each Tournament. In the previous input, it should return the "common" Price object :

Price { 
    value: 2500
    currency: "EUR"
}

But if one of the $currency value is "USD" for example, it should return false.

$last = null;
foreach ($elements as $e) {
  if ($last === null) {
    $last = e->amountStaking;
    continue;
  }
  if ($last->value != $e->value || $last->currence != $e->currency) {
    return false;
  }
  $last = e->amountStaking;
}

return $last;

You walk through the array until one entry does not match the previous one. You return false immediately. If it runs through just return the last object.

Maybe you should

return clone $last;

to make it a new object, in case you want to modify it later.


As requested "Price agnostic":

$last = null;
foreach ($elements as $e) {
  if ($last === null) {
    $last = e->amountStaking;
    continue;
  }
  foreach ($last as $key => $val) {
    if (!property_exists($e, $key) || $last->$key != $e->$key) {
      return false;
    }
  }
  $last = e->amountStaking;
}

return $last;