Skip to content
Advertisement

How do I eliminate 3 lines of repetitive code? [closed]

The three lines repeat themselves twice. How could this be done better?

$selectedComponentsNewTmp = $this->getNewSelectedComponents();
$selectedComponentsNew = [];
foreach ($selectedComponentsNewTmp as $component) {
    $selectedComponentsNew[$component['componentGroup']['Count_0']]['name'] = $component['componentGroup']['name'];
    $selectedComponentsNew[$component['componentGroup']['Count_0']]['value'] = $component['coverage']['value'] ?? '';
    $selectedComponentsNew[$component['componentGroup']['Count_0']]['txt'] = $component['coverage']['txt'] ?? '';
}

$selectedComponentsOldTmp = $this->getOldSelectedComponents();
$selectedComponentsOld = [];
foreach ($selectedComponentsOldTmp as $component) {
    $selectedComponentsOld[$component['componentGroup']['Count_0']]['name'] = $component['componentGroup']['name'];
    $selectedComponentsOld[$component['componentGroup']['Count_0']]['value'] = $component['coverage']['value'] ?? '';
    $selectedComponentsOld[$component['componentGroup']['Count_0']]['txt'] = $component['coverage']['txt'] ?? '';
}

Advertisement

Answer

You could create and use a function:

function

function myFunction($selectedComponentsNew, $component) {
    $selectedComponentsNew[$component['componentGroup']['Count_0']]['name'] = $component['componentGroup']['name'];
    $selectedComponentsNew[$component['componentGroup']['Count_0']]['value'] = $component['coverage']['value'] ?? '';
    $selectedComponentsNew[$component['componentGroup']['Count_0']]['txt'] = $component['coverage']['txt'] ?? '';
}

usage

$selectedComponentsNewTmp = $this->getNewSelectedComponents();
$selectedComponentsNew = [];
foreach ($selectedComponentsNewTmp as $component) {
    myFunction($selectedComponentsNew, $component);
}

$selectedComponentsOldTmp = $this->getOldSelectedComponents();
$selectedComponentsOld = [];
foreach ($selectedComponentsOldTmp as $component) {
    myFunction($selectedComponentsOld, $component);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement