DEV Community

Discussion on: Untangling Nested Code

Collapse
 
hatem20 profile image
Hatem Said • Edited

another bad practice I keep doing in looping,
when I need to create another array form the array I am looping on
I solve this by creating a new array with the same name prefixed by an underscore. but I think there should be a cleaner solution

$_attributeValues = [];

foreach ($attributeValues as $attributeValue) {
foreach ($attributeValue as $attribute => $attributeValueCode) {
$_attributeValues[$attribute][] = $attributeValueCode;
}
}

return $_attributeValues;

Collapse
 
alainvanhout profile image
Alain Van Hout

Typically, when you're transforming an array into another array, there is a specific task that you're trying to accomplish. The name of the new array could reflect that.

Beyond that, method extraction and functional programming can be your friend in these cases.

Collapse
 
gonedark profile image
Jason McCreary

As noted, definitely take a look at the array or collection functions available. The code you posted looks like it is a native group or flatten function.