2

If I have a variable of a type ArrayCollection how do I check if a key of a specific name exists in the collection including nesting. And if it does how do I get and change that value?

2 Answers 2

4

I guess you are talking about Doctrines ArrayCollection \Doctrine\Common\Collections\ArrayCollection.

It does implement phps native ArrayAccess interface, so have a look at the docs. Just check like:

use Doctrine\Common\Collections\ArrayCollection;
$myCollection = new ArrayCollection(array('testKey' => 'testVal'));
var_dump(isset($myCollection['testKey']));

It does also implement its own method from the Collection interface.

/**
 * Checks whether the collection contains an element with the specified key/index.
 *
 * @param string|integer $key The key/index to check for.
 *
 * @return boolean TRUE if the collection contains an element with the specified key/index,
 *                 FALSE otherwise.
 */
public function containsKey($key);

For nested objects there is no build in method, you have to traverse the collection yourself like you would do with a normal array.

Sign up to request clarification or add additional context in comments.

Comments

1

The way that I found was to use the toArray() method in the ArrayCollection object and then use the array_search function:

$newArray = $arrayCollectionObject->toArray();
$keyThatIneed = array_search($value, $newArray);

Comments

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.