2

My object "fields":

array:4 [▼
  0 => Fields {#10900 ▶}
  1 => Fields {#11222 ▶}
  2 => Fields {#11230 ▼
    -id: 8
    -name: "Tier"
    -uuid: "5f60107fe4"
    -productgroup: PersistentCollection {#11231 ▶}
    -options: PersistentCollection {#11233 ▶}
    -template: PersistentCollection {#11235 ▼
      -snapshot: []
      -owner: Fields {#11230}
      -association: array:20 [ …20]
      -em: EntityManager {#4288 …11}
      -backRefFieldName: "fields"
      -typeClass: ClassMetadata {#7714 …}
      -isDirty: false
      #collection: ArrayCollection {#11236 ▼
        -elements: []
      }
      #initialized: true
    }
    -type: Type {#11237 ▶}
    -formatstring: ""
  }
  3 => Fields {#11511 ▶}
]

I want to find out if a certain "templateId" exists in "fields":

foreach ($fields as $field) {
  $templateId = $field->getTemplate();
  $result = property_exists($templateId, 3);    
}

The result is "false", even if I expect it to be true.

Entity field list: https://pastebin.com/zcuFi1dE

Template: https://pastebin.com/mVkKFwJr

1 Answers1

3

First of all,

$templateId = $field->getTemplate();

return an ArrayCollection of Template (By the way you should rename your property Templates)

I believe what you want to do is check if a Template is in the array template of Fields.

So there are two proper ways to do it :

Using the contains method from Doctrine\Common\Collections\ArrayCollection

Compare an object to another

//First get the proper Template object instead of the id
$template = $entityManager->getRepository(Template::class)->find($templateId);
$templateArray = $field->getTemplate();

//return the boolean you want
$templateArray->contains($template);

Compare indexes/keys :

$templateArray = $field->getTemplate();

//return the boolean you want
$templateArray->containsKey($templateId);

But in the case you want to do the same thing but with another property than the id you can loop through your array :

Compare other attribute

//In our case, name for example
$hasCustomAttribute=false;
    foreach($field->getTemplate() as $template){
        if($template->getName() == $nameToTest){
            $hasCustomAttribute=true;
        }
    }
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • Thank you. Not exactly. In the ArrayCollection "Template" I have for example 4 templates. All with different Ids. Somethimes (1,2,3,4) sometimes only (1,2) sometimes (3) etc. I need to check for each field if itcontains the template with the Id "3". Do you know how I mean? –  Apr 15 '19 at 12:05
  • Is this also possible without using another loop? For example array_key_exists? –  Apr 15 '19 at 12:09
  • If I want to check by "uuid" I cannot use containsKey for example –  Apr 15 '19 at 12:20