ArrayCollection

class ArrayCollection implements Collection, Selectable

An ArrayCollection is a Collection implementation that wraps a regular PHP array.

Methods

public __construct(array $elements = array()) Initializes a new ArrayCollection.
public arraytoArray() Gets a native PHP array representation of the collection.
public mixedfirst() Sets the internal iterator to the first element in the collection and returns this element.
public mixedlast() Sets the internal iterator to the last element in the collection and returns this element.
public int|stringkey() Gets the key/index of the element at the current iterator position.
public mixednext() Moves the internal iterator position to the next element and returns this element.
public mixedcurrent() Gets the element of the collection at the current iterator position.
public mixedremove(string|integer $key) Removes the element at the specified index from the collection.
public booleanremoveElement(mixed $element) Removes the specified element from the collection, if it is found.
public offsetExists($offset) Required by interface ArrayAccess.
public offsetGet($offset) Required by interface ArrayAccess.
public offsetSet($offset, $value) Required by interface ArrayAccess.
public offsetUnset($offset) Required by interface ArrayAccess.
public booleancontainsKey(string|integer $key) Checks whether the collection contains an element with the specified key/index.
public booleancontains(mixed $element) Checks whether an element is contained in the collection.
public booleanexists(Closure $p) Tests for the existence of an element that satisfies the given predicate.
public int|string|boolindexOf(mixed $element) Gets the index/key of a given element. The comparison of two elements is strict, that means not only the value but also the type must match.
public mixedget(string|integer $key) Gets the element at the specified key/index.
public arraygetKeys() Gets all keys/indices of the collection.
public arraygetValues() Gets all values of the collection.
public count() {@inheritDoc}
public voidset(string|integer $key, mixed $value) Sets an element in the collection at the specified key/index.
public booleanadd($value) Adds an element at the end of the collection.
public booleanisEmpty() Checks whether the collection is empty (contains no elements).
public getIterator() Required by interface IteratorAggregate.
public Collectionmap(Closure $func) Applies the given function to each element in the collection and returns a new collection with the elements returned by the function.
public Collectionfilter(Closure $p) Returns all the elements of this collection that satisfy the predicate p.
public booleanforAll(Closure $p) Tests whether the given predicate p holds for all elements of this collection.
public arraypartition(Closure $p) Partitions this collection in two collections according to a predicate.
public string__toString() Returns a string representation of this object.
public voidclear() Clears the collection, removing all elements.
public arrayslice(int $offset, int|null $length = null) Extracts a slice of $length elements starting at position $offset from the Collection.
public Collectionmatching(Criteria $criteria) Selects all elements from a selectable that match the expression and returns a new collection containing these elements.

Details

at line 48

__construct()

public __construct(array $elements = array())

Initializes a new ArrayCollection.

Parameters

array$elements
at line 56

toArray()

public array toArray()

Gets a native PHP array representation of the collection.

Return Value

array
at line 64

first()

public mixed first()

Sets the internal iterator to the first element in the collection and returns this element.

Return Value

mixed
at line 72

last()

public mixed last()

Sets the internal iterator to the last element in the collection and returns this element.

Return Value

mixed
at line 80

key()

public int|string key()

Gets the key/index of the element at the current iterator position.

Return Value

int|string
at line 88

next()

public mixed next()

Moves the internal iterator position to the next element and returns this element.

Return Value

mixed
at line 96

current()

public mixed current()

Gets the element of the collection at the current iterator position.

Return Value

mixed
at line 104

remove()

public mixed remove(string|integer $key)

Removes the element at the specified index from the collection.

Parameters

string|integer$keyThe kex/index of the element to remove.

Return Value

mixedThe removed element or NULL, if the collection did not contain the element.
at line 119

removeElement()

public boolean removeElement(mixed $element)

Removes the specified element from the collection, if it is found.

Parameters

mixed$elementThe element to remove.

Return Value

booleanTRUE if this collection contained the specified element, FALSE otherwise.
at line 137

offsetExists()

public offsetExists($offset)

Required by interface ArrayAccess.

{@inheritDoc}

Parameters

$offset
at line 147

offsetGet()

public offsetGet($offset)

Required by interface ArrayAccess.

{@inheritDoc}

Parameters

$offset
at line 157

offsetSet()

public offsetSet($offset, $value)

Required by interface ArrayAccess.

{@inheritDoc}

Parameters

$offset
$value
at line 171

offsetUnset()

public offsetUnset($offset)

Required by interface ArrayAccess.

{@inheritDoc}

Parameters

$offset
at line 179

containsKey()

public boolean containsKey(string|integer $key)

Checks whether the collection contains an element with the specified key/index.

Parameters

string|integer$keyThe key/index to check for.

Return Value

booleanTRUE if the collection contains an element with the specified key/index, FALSE otherwise.
at line 187

contains()

public boolean contains(mixed $element)

Checks whether an element is contained in the collection.

This is an O(n) operation, where n is the size of the collection.

Parameters

mixed$elementThe element to search for.

Return Value

booleanTRUE if the collection contains the element, FALSE otherwise.
at line 195

exists()

public boolean exists(Closure $p)

Tests for the existence of an element that satisfies the given predicate.

Parameters

Closure$pThe predicate.

Return Value

booleanTRUE if the predicate is TRUE for at least one element, FALSE otherwise.
at line 209

indexOf()

public int|string|bool indexOf(mixed $element)

Gets the index/key of a given element. The comparison of two elements is strict, that means not only the value but also the type must match.

For objects this means reference equality.

Parameters

mixed$elementThe element to search for.

Return Value

int|string|boolThe key/index of the element or FALSE if the element was not found.
at line 217

get()

public mixed get(string|integer $key)

Gets the element at the specified key/index.

Parameters

string|integer$keyThe key/index of the element to retrieve.

Return Value

mixed
at line 225

getKeys()

public array getKeys()

Gets all keys/indices of the collection.

Return Value

arrayThe keys/indices of the collection, in the order of the corresponding elements in the collection.
at line 233

getValues()

public array getValues()

Gets all values of the collection.

Return Value

arrayThe values of all elements in the collection, in the order they appear in the collection.
at line 241

count()

public count()

{@inheritDoc}

at line 249

set()

public void set(string|integer $key, mixed $value)

Sets an element in the collection at the specified key/index.

Parameters

string|integer$keyThe key/index of the element to set.
mixed$valueThe element to set.

Return Value

void
at line 257

add()

public boolean add($value)

Adds an element at the end of the collection.

Parameters

$value

Return Value

booleanAlways TRUE.
at line 267

isEmpty()

public boolean isEmpty()

Checks whether the collection is empty (contains no elements).

Return Value

booleanTRUE if the collection is empty, FALSE otherwise.
at line 277

getIterator()

public getIterator()

Required by interface IteratorAggregate.

{@inheritDoc}

at line 285

map()

public Collection map(Closure $func)

Applies the given function to each element in the collection and returns a new collection with the elements returned by the function.

Parameters

Closure$func

Return Value

Collection
at line 293

filter()

public Collection filter(Closure $p)

Returns all the elements of this collection that satisfy the predicate p.

The order of the elements is preserved.

Parameters

Closure$pThe predicate used for filtering.

Return Value

CollectionA collection with the results of the filter operation.
at line 301

forAll()

public boolean forAll(Closure $p)

Tests whether the given predicate p holds for all elements of this collection.

Parameters

Closure$pThe predicate.

Return Value

booleanTRUE, if the predicate yields TRUE for all elements, FALSE otherwise.
at line 315

partition()

public array partition(Closure $p)

Partitions this collection in two collections according to a predicate.

Keys are preserved in the resulting collections.

Parameters

Closure$pThe predicate on which to partition.

Return Value

arrayAn array with two elements. The first element contains the collection of elements where the predicate returned TRUE, the second element contains the collection of elements where the predicate returned FALSE.
at line 335

__toString()

public string __toString()

Returns a string representation of this object.

Return Value

string
at line 343

clear()

public void clear()

Clears the collection, removing all elements.

Return Value

void
at line 351

slice()

public array slice(int $offset, int|null $length = null)

Extracts a slice of $length elements starting at position $offset from the Collection.

If $length is null it returns all elements from $offset to the end of the Collection. Keys have to be preserved by this method. Calling this method will only return the selected slice and NOT change the elements contained in the collection slice is called on.

Parameters

int$offsetThe offset to start from.
int|null$lengthThe maximum number of elements to return, or null for no limit.

Return Value

array
at line 359

matching()

public Collection matching(Criteria $criteria)

Selects all elements from a selectable that match the expression and returns a new collection containing these elements.

Parameters

Criteria$criteria

Return Value

Collection

Source code

<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\Common\Collections;

use ArrayIterator;
use Closure;
use Doctrine\Common\Collections\Expr\ClosureExpressionVisitor;

/**
 * An ArrayCollection is a Collection implementation that wraps a regular PHP array.
 *
 * @since  2.0
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 */
class ArrayCollection implements Collection, Selectable
{
    /**
     * An array containing the entries of this collection.
     *
     * @var array
     */
    private $elements;

    /**
     * Initializes a new ArrayCollection.
     *
     * @param array $elements
     */
    public function __construct(array $elements = array())
    {
        $this->elements = $elements;
    }

    /**
     * {@inheritDoc}
     */
    public function toArray()
    {
        return $this->elements;
    }

    /**
     * {@inheritDoc}
     */
    public function first()
    {
        return reset($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function last()
    {
        return end($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function key()
    {
        return key($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function next()
    {
        return next($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function current()
    {
        return current($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function remove($key)
    {
        if ( ! isset($this->elements[$key]) && ! array_key_exists($key, $this->elements)) {
            return null;
        }

        $removed = $this->elements[$key];
        unset($this->elements[$key]);

        return $removed;
    }

    /**
     * {@inheritDoc}
     */
    public function removeElement($element)
    {
        $key = array_search($element, $this->elements, true);

        if ($key === false) {
            return false;
        }

        unset($this->elements[$key]);

        return true;
    }

    /**
     * Required by interface ArrayAccess.
     *
     * {@inheritDoc}
     */
    public function offsetExists($offset)
    {
        return $this->containsKey($offset);
    }

    /**
     * Required by interface ArrayAccess.
     *
     * {@inheritDoc}
     */
    public function offsetGet($offset)
    {
        return $this->get($offset);
    }

    /**
     * Required by interface ArrayAccess.
     *
     * {@inheritDoc}
     */
    public function offsetSet($offset, $value)
    {
        if ( ! isset($offset)) {
            return $this->add($value);
        }

        $this->set($offset, $value);
    }

    /**
     * Required by interface ArrayAccess.
     *
     * {@inheritDoc}
     */
    public function offsetUnset($offset)
    {
        return $this->remove($offset);
    }

    /**
     * {@inheritDoc}
     */
    public function containsKey($key)
    {
        return isset($this->elements[$key]) || array_key_exists($key, $this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function contains($element)
    {
        return in_array($element, $this->elements, true);
    }

    /**
     * {@inheritDoc}
     */
    public function exists(Closure $p)
    {
        foreach ($this->elements as $key => $element) {
            if ($p($key, $element)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function indexOf($element)
    {
        return array_search($element, $this->elements, true);
    }

    /**
     * {@inheritDoc}
     */
    public function get($key)
    {
        return isset($this->elements[$key]) ? $this->elements[$key] : null;
    }

    /**
     * {@inheritDoc}
     */
    public function getKeys()
    {
        return array_keys($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function getValues()
    {
        return array_values($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function count()
    {
        return count($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function set($key, $value)
    {
        $this->elements[$key] = $value;
    }

    /**
     * {@inheritDoc}
     */
    public function add($value)
    {
        $this->elements[] = $value;

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function isEmpty()
    {
        return empty($this->elements);
    }

    /**
     * Required by interface IteratorAggregate.
     *
     * {@inheritDoc}
     */
    public function getIterator()
    {
        return new ArrayIterator($this->elements);
    }

    /**
     * {@inheritDoc}
     */
    public function map(Closure $func)
    {
        return new static(array_map($func, $this->elements));
    }

    /**
     * {@inheritDoc}
     */
    public function filter(Closure $p)
    {
        return new static(array_filter($this->elements, $p));
    }

    /**
     * {@inheritDoc}
     */
    public function forAll(Closure $p)
    {
        foreach ($this->elements as $key => $element) {
            if ( ! $p($key, $element)) {
                return false;
            }
        }

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function partition(Closure $p)
    {
        $matches = $noMatches = array();

        foreach ($this->elements as $key => $element) {
            if ($p($key, $element)) {
                $matches[$key] = $element;
            } else {
                $noMatches[$key] = $element;
            }
        }

        return array(new static($matches), new static($noMatches));
    }

    /**
     * Returns a string representation of this object.
     *
     * @return string
     */
    public function __toString()
    {
        return __CLASS__ . '@' . spl_object_hash($this);
    }

    /**
     * {@inheritDoc}
     */
    public function clear()
    {
        $this->elements = array();
    }

    /**
     * {@inheritDoc}
     */
    public function slice($offset, $length = null)
    {
        return array_slice($this->elements, $offset, $length, true);
    }

    /**
     * {@inheritDoc}
     */
    public function matching(Criteria $criteria)
    {
        $expr     = $criteria->getWhereExpression();
        $filtered = $this->elements;

        if ($expr) {
            $visitor  = new ClosureExpressionVisitor();
            $filter   = $visitor->dispatch($expr);
            $filtered = array_filter($filtered, $filter);
        }

        if ($orderings = $criteria->getOrderings()) {
            foreach (array_reverse($orderings) as $field => $ordering) {
                $next = ClosureExpressionVisitor::sortByField($field, $ordering == Criteria::DESC ? -1 : 1);
            }

            uasort($filtered, $next);
        }

        $offset = $criteria->getFirstResult();
        $length = $criteria->getMaxResults();

        if ($offset || $length) {
            $filtered = array_slice($filtered, (int)$offset, $length);
        }

        return new static($filtered);
    }
}