0

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

Pierre
  • 490
  • 1
  • 7
  • 26

2 Answers2

1

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.

Jeto
  • 14,596
  • 2
  • 32
  • 46
  • 1
    I really like this one, I was looking for that ! Now, I just have to create an array as component which contains all my array and here we go ! Thanks ! – Pierre Dec 16 '19 at 12:08
  • It just avoid to call X times my function, once for each array... Imagine if I had like 100 arrays, impossible – Pierre Dec 16 '19 at 12:09
  • 1
    I think it should be `&$components` in the outer loop. Otherwise copies will be created – AterLux Dec 16 '19 at 12:18
  • @AterLux Actually, not in PHP7 at least. The copy will only occur if you modify the array. See [this answer](https://stackoverflow.com/a/34099166/965834) or even [this complete one](https://stackoverflow.com/a/14854568/965834). Should be avoided. – Jeto Dec 16 '19 at 12:42
  • @Jeto thats right for earlier version of PHP too, but it is not what I was talking about. Note `&$component` in the code. That means intention to modify values of array items. Although `$cpus` and `$rams` also has to be passed by reference to do that. – AterLux Dec 16 '19 at 15:24
  • Oh, my bad, you're right. Edited the answer, thanks for your comments! – Jeto Dec 16 '19 at 16:00
0

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;
}
dhamo
  • 545
  • 2
  • 7