Use PHP Recursion to Calculate the Sum of Multi-dimensional Arrays

 ← Dev Articles
👍 0
👎 0

For this example I will use PHP to create a script that calculates the sum of a multi-dimensional array of integers.   We need a recursive method to do this.  Well not necessarily in this example because the dimensions of array $numbers is known. So we can just use standard for, foreach or while loops embedded to traverse the array.  However when the structure of $numbers is unknown, recursion is necessary.  

Infact, the only way to traverse this kind of array is with recursion.  At some point you will need to learn recursion.  This example breaks things down and makes it easy to understand.


$numbers = [

   2,

   7,

   5,

   [

       4,

       8,

       6

   ],

   [

       2,

       3,

       [

           9,

           3,

           6

       ],

       4,

       5

   ],

   [

       7,

       8,

       9,

       [

           5,

           5,

           4

       ]

   ]

 ];

 

 function calculate($input)

 {   

   $sum = !is_array($input) ? $input : 0;

   if(is_array($input))

   {

       foreach($input as $child)

       {

           $sum += calculate($child);

       }

   }

   return $sum;

 }

 

 $sum = calculate($numbers);

 

// Ouput: 102

 

 
So recursion is especially useful for traversing a multi-dimensional array where the depth/dimensions are unknown so typical for, while and foreach loops don't work.