1

More of a curiosity question. If you have an array of arrays, is there any shorthand for iterating over the interior arrays? You can obviously use the following to do it, but I wondered if there's a single line call that gets rid of the second foreach.

$arr = array(array(1,2,3), array(4,5,6), array(7,8,9));
foreach($arr as $interiorArr)
{
   foreach($interiorArr as $number)
   {
     echo $number;
   }
}

output would be "123456789"

Andrew
  • 472
  • 5
  • 18
  • 1
    I think it would be best to do something like this: https://stackoverflow.com/a/1320259/5884896 – drussey Jan 05 '21 at 21:11
  • Does this answer your question? [How to Flatten a Multidimensional Array?](https://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) – showdev Jan 05 '21 at 21:23
  • I just provided a very simple data example. I was more looking for some syntax that might exist to structure the code more like "foreachMember($arr as $number){echo $number;} Something to save those 3 lines of code and make it more readable. Every nest can add confusion to someone not familiar with the code. – Andrew Jan 06 '21 at 15:07

1 Answers1

2

Depending on what you're needing to do, you can recursively walk the array:

array_walk_recursive($arr, function($v) { echo $v; });

For this simple example (echo and print aren't functions so can't be used as a callback):

array_walk_recursive($arr, 'printf');

Again, depending on what you're needing to do, and for this simple example, you can foreach and use a variety of functions that operates on arrays:

foreach($arr as $interiorArr)
{
     echo implode($interiorArr);
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • For this simple example yes I agree with your implode, but if the logic in the nested function is more complex not so much. I suppose you could write another function for your logic and walk it recursively, but I don't see how that would simplify the code in any way. – Andrew Jan 06 '21 at 15:02