John Davidson

php - How to refactor similar foreach loops to follow DRY approach

0 comments
Message:


If you have foreach loops of multiple arrays, and you need to run one of them inside another - Is it possible to refactor the following code to only have one loop to stop duplicating code:


<?php

$apples = array(
'red',
);

$bananas = array(
'yellow',
);

foreach ( $apples => $apple ) {
echo '<div class="apple">' . $apple . '</div>';
}

foreach ( $bananas => $banana ) {
echo '<div class="banana">';
echo $banana;
echo '<div class="child">';
foreach ( $apples => $apple ) {
echo '<div class="apple">' . $apple . '</div>';
}
echo '</div>';
echo '</div>';
}

/*
output:
<div class="apple">red</div>
<div class="banana">
yellow
<div class="child">
<div class="apple">red</div>
</div>
</div>
*/

This code logic that is duplicate is the one that outputs the <div class="apple">red</div>:


foreach ( $apples => $apple ) {
echo '<div class="apple">' . $apple . '</div>';
}


My Answer:
To refactor the code to follow the DRY (Don't Repeat Yourself) approach, you can combine the two arrays into a single multidimensional array and then use a single foreach loop to iterate over both arrays. Here's how you can do it:

php

$fruits = array(
'apples' => array(
'color' => 'red',
),
'bananas' => array(
'color' => 'yellow',
),
);

foreach ( $fruits as $fruitType => $fruit ) {
echo '
';
echo $fruit['color'];

if ($fruitType == 'bananas') {
echo '
';
foreach ( $fruits['apples'] as $apple ) {
echo '
' . $apple['color'] . '
';
}
echo '
';
}

echo '
';
}

/*
output:
red


yellow

red



*/


In this refactored code, we have combined the 'apples' and 'bananas' arrays into a single multidimensional array called $fruits. We then use a single foreach loop to iterate over this array and output the corresponding HTML. The inner foreach loop is used only when the fruit type is 'bananas'. This way, we have eliminated the duplicate code and followed the DRY principle.

Rate this post

4 of 5 based on 3369 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us