patternphpMinor
Returning nested array with added key=>value
Viewed 0 times
arraywithaddedvaluenestedreturningkey
Problem
This works, but do I have to make a new array,
Won't this way take up more memory needlessly?
result, or is there a way to just insert the field I need into each $key of the received parameter $data?Won't this way take up more memory needlessly?
function add_tax($data){
$result = [];
foreach($data as $product => $details) {
$details['tax'] = 0;
$result[$product] = $details;
}
return $result;
}Solution
You could try something along these lines:
EDIT 1:
After a bit more researching on foreach I have come up with the following alternative:
In reference to Alex L: I apologize, the original answer was rushed. The first snippet was simply a way of answering the question, that yes, it is possible to iterate through
NOTE: The unset in the function is not exactly necessary, but as your question referenced memory usage, unset breaks the reference and releases that memory.
EDIT 2:
Due to very strong backing in the comments, I've removed the call to unset (truth be told I'd never use it myself, but wanted to reference it's usage within the function)
function add_tax($data){
foreach($data as $product => $details) {
$data[$product]['tax'] = 0;
}
return $data;
}EDIT 1:
After a bit more researching on foreach I have come up with the following alternative:
function add_tax(&$data) {
foreach($data as &$details)
$details['tax'] = 0;
}In reference to Alex L: I apologize, the original answer was rushed. The first snippet was simply a way of answering the question, that yes, it is possible to iterate through
$data without generating a new variable. Also, to MikeiLL, yes, that would be a waste of memory. This second snippet passes both variables by reference, which does not require any excess usage of memory. It is the most optimal format of this process.NOTE: The unset in the function is not exactly necessary, but as your question referenced memory usage, unset breaks the reference and releases that memory.
EDIT 2:
Due to very strong backing in the comments, I've removed the call to unset (truth be told I'd never use it myself, but wanted to reference it's usage within the function)
Code Snippets
function add_tax($data){
foreach($data as $product => $details) {
$data[$product]['tax'] = 0;
}
return $data;
}function add_tax(&$data) {
foreach($data as &$details)
$details['tax'] = 0;
}Context
StackExchange Code Review Q#57314, answer score: 4
Revisions (0)
No revisions yet.