Laravel Collections Using Array Syntax


Example

The Collection object implements the ArrayAccess and IteratorAggregate interface, allowing it to be used like an array.

Access collection element:

 $collection = collect([1, 2, 3]);
 $result = $collection[1];

Result: 2

Assign new element:

$collection = collect([1, 2, 3]);
$collection[] = 4;

Result: $collection is [1, 2, 3, 4]

Loop collection:

$collection = collect(["a" => "one", "b" => "two"]);
$result = "";
foreach($collection as $key => $value){
    $result .= "(".$key.": ".$value.") ";        
}

Result: $result is (a: one) (b: two)

Array to Collection conversion:

To convert a collection to a native PHP array, use:

$array = $collection->all();
//or
$array = $collection->toArray()

To convert an array into a collection, use:

$collection = collect($array);

Using Collections with Array Functions

Please be aware that collections are normal objects which won't be converted properly when used by functions explicitly requiring arrays, like array_map($callback).

Be sure to convert the collection first, or, if available, use the method provided by the Collection class instead: $collection->map($callback)