Pierre
Pierre

Reputation: 510

How to avoid to duplicate foreach if the logic is the same for all array?

This question is about how to produce a better code in PHP.

I've multiple arrays (5 to be exact). I've to apply the same logic to all of them. How can I avoid to duplicate the code for all of them ?

$cpus = getCPUs(); // Get array 1 dimension with key
$rams = getRAMs(); // Get array 1 dimension with key

I mean, the code inside, I just have to create a function. That's OK. But I still have to declare one foreach loop for each array...

Is there a way to avoid that ? It's like to have my foreach loop parameters from variables.

foreach ($cpus as $key_cpu => &$cpu) {
    // FUNCTION XXX
}

foreach ($rams as $key_ram => &$ram) {
    // FUNCTION XXX
}

Regards

Upvotes: 0

Views: 100

Answers (2)

Jeto
Jeto

Reputation: 14927

You could simply use two foreachs:

foreach ([&$cpus, &$rams] as &$components) {
  foreach ($components as $key => &$component) {
     // FUNCTION XXX
  }
}

Note that all those references are needed to be able to assign another value to $component and have it also modify the original values (like the question suggested). Ideally you'd want to avoid doing that if you can. If these components are arrays, explore using objects instead.

Thanks to @AterLux for the helpful comments below.

Upvotes: 1

dhamo
dhamo

Reputation: 555

write common function/method for loop all array and return whatever your want...

function loop_array($array){

    $return_data=array()
    foreach ($array as $key => &$data) {

            // FUNCTION XXX
    }

    return $return_data;
}

Upvotes: 0

Related Questions