Home > Mobile >  Laravel 8 variable value from aggregate sum of multiple column values
Laravel 8 variable value from aggregate sum of multiple column values

Time:02-13

I need to create a variable thats the aggregate sum of multiple values. I have about 25 values to to add together--below is a small snippet. The below works, but stringing all the values together with a seems a bit dirty. Is there another way?

// Calculate Modification Points
        $trackPTS = $this->track ? 20 : 0;
        $shockTowerPTS = $this->shock_tower ? 10 : 0;
        $loweringPTS = $this->lowering ? 10 : 0;
        $camberPTS = $this->camber ? 20 : 0;
        $monoballPTS = $this->monoball ? 10 : 0;
        $tubeFramePTS = $this->tube_frame ? 100 : 0;
        $pasmPTS = $this->pasm ? 20 : 0;
        $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;

        $totalModificationPoints = $treadWearPoints   $trackPTS   $shockTowerPTS   $loweringPTS   $camberPTS   $monoballPTS   $tubeFramePTS   $pasmPTS   $rearAxleSteerPTS;

CodePudding user response:

This is one other way of doing the same thing.

$totalModificationPoints = 0; //initial value

$totalModificationPoints  = $trackPTS = $this->track ? 20 : 0;
$totalModificationPoints  = $shockTowerPTS = $this->shock_tower ? 10 : 0;
$totalModificationPoints  = $loweringPTS = $this->lowering ? 10 : 0;
$totalModificationPoints  = $camberPTS = $this->camber ? 20 : 0;
$totalModificationPoints  = $monoballPTS = $this->monoball ? 10 : 0;
$totalModificationPoints  = $tubeFramePTS = $this->tube_frame ? 100 : 0;
$totalModificationPoints  = $pasmPTS = $this->pasm ? 20 : 0;
$totalModificationPoints  = $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;

CodePudding user response:

I would put all possible class variable names to an array and then i would iterate it. Like that:

<?php
class Calc {
 
  private $track = 30;
  private $shock_tower = 40;
  private $lowering = 10;
  
  public function __construct() {    
    $keyValues = [
        ['track', 20],
        ['shock_tower', 10],
        ['lowering', 10],
    ];

    $sum = 0;
    foreach($keyValues as $set) {        
        $sum  = (int) $this->{$set[0]} ?? $set[1];
    }

    print_r($sum);
  }
}

new Calc();
  • Related