-1

I need to perform a calculation in a loop whereby every other iteration should change + to - and vice versa.

$mainNumber = 6;
$finalData = [];
$operator = '+';
for ($i = 1; $i <= $mainNumber; $i++) {
    switch ($operator) {
        case '-':
            $operator = '+';
            break;

        case '+':
            $operator = '-';
            break;
    }
    $finalData[] = "$mainNumber $operator $i";
}
dd($finalData);

My above code output as follows

array:5 [▼
  0 => "6 - 1"
  1 => "6 + 2"
  2 => "6 - 3"
  3 => "6 + 4"
  4 => "6 - 5"
  5 => "6 + 6"
]

Instead

array:5 [▼
  0 => "5"
  1 => "8"
  2 => "3"
  3 => "10"
  4 => "1"
  5 => "12"
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
zarpio
  • 10,380
  • 8
  • 58
  • 71

2 Answers2

3

Rather than creating a string (which you would then need to eval) just perform the computation in your loop:

$mainNumber = 6;
$finalData = [];
$operator = '-';
for ($i = 1; $i <= $mainNumber; $i++) {
    switch ($operator) {
        case '-':
            $finalData[] = $mainNumber - $i;
            $operator = '+';
            break;
        case '+':
            $finalData[] = $mainNumber + $i;
            $operator = '-';
            break;
    }
}
print_r($finalData);

Output:

Array ( 
    [0] => 5
    [1] => 8
    [2] => 3
    [3] => 10 
    [4] => 1 
    [5] => 12
 )

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
1

I find switch blocks to be horrifically verbose. You can just use math in a one-liner.

If $i is odd, set it as a negative factor in the equation. In other words, you always add a positive or negative value of $i to $mainNumber.

Code: (Demo)

$mainNumber = 6;
$finalData = [];
for ($i = 1; $i <= $mainNumber; ++$i) {
    $finalData[] = $mainNumber + (($i & 1 ? -1 : 1) * $i);
}
var_export($finalData);

Output:

array (
  0 => 5,
  1 => 8,
  2 => 3,
  3 => 10,
  4 => 1,
  5 => 12,
)

Additional notes:

Switch blocks are most valuable when you need to evaluate the same condition multiple times and check the result against predictable static, singular values. This situation only need to check if the operator is plus or minus -- in other words if-else. There is no value to implementing a switch case here.

Using eval() may be safe to use with the trustworthy values in this question, but when user-supplied data is involved, eval() grows horns and carroes a pitchfork -- the general advice from nearly all professional developers is to avoid the function call.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136