Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bwrigley's avatar

Adding items to an array in a Collection

I'm sure I'm missing something obvious here but I can't seem to find the answer in the docs anywhere.

If I create a new collection like :

$coll = new Collection([
    'metrics' => [],
    'dimensions' => [],
]);

how do I push new values into the metrics array?

0 likes
7 replies
gcunha's avatar

Can you try:

$coll->put(
    'metrics', 
    array_push($coll->get('metrics'), $value)
);
bwrigley's avatar

Some trial and error suggests that maybe I shouldn't be adding metrics as an array?

$coll = new Collection([
    'metrics' => collect(),
    'dimensions' => collect(),
]);

then I can push with:

$coll->get('metrics')->push('a new thing');

Would be grateful to know if this really is best practice?

bwrigley's avatar

Sorry our messages overlapped:

So I tried what you suggested in tinker:

$coll->put(
     'metrics', 
     array_push($coll->get('metrics'), 'something')
);

PHP Notice: Only variables should be passed by reference in /home/vagrant/Code/everyone-in-mindeval()'d code on line 1

AddWebContribution's avatar

You should try this:

$coll = new Collection([
    'metrics' => [],
    'dimensions' => [],
]);

$newArray = ["test"=>"details"];

$coll = array_merge($coll,$newArray);
1 like
gcunha's avatar

Yeah, seems we cannot inline this $coll->get('metrics') in array_push, you would have to extract it to an auxiliar variable.

bwrigley's avatar

This works well, but actually I think that a Collection of Collections is probably more elegant. Is it bad form to mark my own solution as 'Best Answer' 😫

localpathcomp's avatar

You can use the spread operator in PHP to help. This ensures an immutable/functional way to update your array. Given:

$collection = collect([
    'metrics' => ['original thing'],
    'dimensions' => [],
]);

$collection->put('metrics', [
  ...$collection['metrics'],
  'a new thing'
]);
1 like

Please or to participate in this conversation.