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?
Can you try:
$coll->put(
'metrics',
array_push($coll->get('metrics'), $value)
);
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?
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
You should try this:
$coll = new Collection([
'metrics' => [],
'dimensions' => [],
]);
$newArray = ["test"=>"details"];
$coll = array_merge($coll,$newArray);
Yeah, seems we cannot inline this $coll->get('metrics') in array_push, you would have to extract it to an auxiliar variable.
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' 😫
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'
]);
Please sign in or create an account to participate in this conversation.