0

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.

2
  • your input array is object type array or normal php array? Also what happen if there are more than two element in the input array? Also what you have tried? post it here, so that we can get clear idea. Commented Dec 12, 2016 at 15:35
  • my input is a object type array (Doctrine ArrayCollection). If there are more than 2 elements in the input array, it should behave as explain. If all the $amountStaking are equals, it should return the common Price object. it at least one is different, returns false. Right now I didn't write any code. I read about array_column, array_diff and a bunch of other functions, but have no idea how to mix that all together Commented Dec 12, 2016 at 15:39

1 Answer 1

1
$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;
Sign up to request clarification or add additional context in comments.

2 Comments

any way to make it Price agnostic ? I mean if tomorrow I had a property inside Price object, I don't have to update the if() statement to reflect the new property.
Added a version for that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.