schroedingerswg's avatar

Is there a better way to reduce an array in php

I mean, in js there is sum=array.reduce(product=>product.daily_rent);

 19     public function daily_rent() {                    
 20         $sum=0;                                       
 21         foreach($this->products as $product) {        
 22             $sum+=$product->daily_rent*$product->pivot->quantity;      
 23         }
 24         return $sum;                                  
 25     }
 26 
 27 
 28     public function sale_price() {
 29         $sum=0;
 30         foreach($this->products as $product) {
 31             $sum+=$product->sale_price*$product->pivot->quantity;      
 32         }
 33         return $sum;
 34     }
 35 
 36     public function deposit() {
 37         $sum=0;                                       
 38         foreach($this->products as $product) {        
 39             $sum+=$product->deposit*$product->pivot->quantity;         
 40         }                                             
 41         return $sum;                                  
 42         /* eg something like this?!?
 43         return array_reduce($this->products->toArray(), function($product) {
 44             return $product["deposit"];
 45             //return $product->deposit;
 46         }, 0);
 47          */
 48 
 49     }
 50 
0 likes
4 replies
adamprickett's avatar

The array_reduce callback accepts 2 arguments - the $carry and the $item

The callback needs to return the the value you wish to pass into the next iteration as $carry, for example:

return array_reduce($this->products->toArray(), function($carry, $product) {
    return $carry + $product["deposit"];
}, 0);
2 likes

Please or to participate in this conversation.