To add elements to a collection in Illuminate/Collections, you can use the push()
method or the put()
method, depending on the type of collection you are working with.
Here is an example using both methods:
push()
method:use Illuminate\Support\Collection;
$collection = new Collection();
$collection->push('element1');
$collection->push('element2');
$collection->push('element3');
print_r($collection->all());
This will output:
Array
(
[0] => element1
[1] => element2
[2] => element3
)
put()
method on an associative array collection:use Illuminate\Support\Collection;
$collection = new Collection();
$collection->put('key1', 'value1');
$collection->put('key2', 'value2');
$collection->put('key3', 'value3');
print_r($collection->all());
This will output:
Array
(
[key1] => value1
[key2] => value2
[key3] => value3
)
Note: If you are working with an instance of a specific Illuminate collection class like Illuminate\Support\Collection
, you can add elements to the collection using the push()
or put()
methods directly on the instance. However, if you are working with a generic Illuminate\Support\Collection
instance, you can also add elements using array-like syntax like $collection[] = 'element';
or $collection['key'] = 'value';
.