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
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;
}
}