1

I've array of objects

$states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();

How can I check if $states contains object with data?

LocationState {#102960 ▼
  -id: 1
  -ident: "02"
  -name: "NAME"
  -country: LocationCountry {#102992 ▶}
}

This is no ArrayCollection but Array of Objects.

nicram
  • 353
  • 3
  • 7
  • 24
  • What do you mean by `contains object with data` ? – goto Jan 22 '18 at 17:35
  • Yes, exacly. object with spcecific data. I want to check if array contains object with ident == 02 and name == NAME. I can write forech which will be looping for array but I think It's not good idea because of performance – nicram Jan 22 '18 at 17:43
  • Possible duplicate of [Doctrine 2 ArrayCollection filter method](https://stackoverflow.com/questions/8334356/doctrine-2-arraycollection-filter-method) – goto Jan 22 '18 at 17:50

2 Answers2

1

For array of objects:

$found = !empty(array_filter($objects, function ( $obj ) {
    return $obj->name == 'NAME' && $obj->id == 1;
}));

For ArrayCollection:

$found = $objects->exists(function ( $obj ) {
    return $obj->name == 'NAME' && $obj->id == 1;
});
Dominique Lorre
  • 1,168
  • 1
  • 10
  • 19
xurshid29
  • 4,172
  • 1
  • 20
  • 25
0

If you want them to be retrieved by the query:

$this->getDoctrine()->getRepository(LocationState::class)
  ->findBy(['name' => 'NAME', 'ident' => '02']);

If you just want to know if a specified object is on your collection, you will have to use some code

 $states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();

  $found = false;
  foreach($state in $states) {
    if($state->getName() == 'NAME' && $state->getIdent() == '02' ) {
      $found = true;
    }
  }

Doctrine 2 ArrayCollection filter method

goto
  • 7,908
  • 10
  • 48
  • 58
  • It's the second issue. I have to find specified object in collection. I've made similar function. I thought that is some kind of php or doctrine helper function to do this. Thanks a lot. – nicram Jan 22 '18 at 17:55