How to toggle mathematical operator and store calculations in a loop?calculate math expression from a string using evalHow do I loop through or enumerate a JavaScript object?How do I break out of nested loops in Java?How to break out of jQuery each LoopReference — What does this symbol mean in PHP?How to toggle a boolean?Reference - What does this error mean in PHP?How do I determine whether my calculation of pi is accurate?Ways to iterate over a list in JavaSolving Math Expression in loops and storing in a dataframe with RCalculation in a loop in R

Are the Night's Watch still required?

Trigonometry substitution issue with sign

When an imagined world resembles or has similarities with a famous world

Should I mention being denied entry to UK due to a confusion in my Visa and Ticket bookings?

Does XQuartz work on macOS Mojave?

Is there a word that describes the unjustified use of a more complex word?

History of the kernel of a homomorphism?

Copy previous line to current line from text file

Where are the "shires" in the UK?

Is 'contemporary' ambiguous and if so is there a better word?

GitLab account hacked and repo wiped

Is any special diet an effective treatment of autism?

How should I tell my manager I'm not paying for an optional after work event I'm not going to?

Why is "breaking the mould" positively connoted?

Is Benjen dead?

What to use instead of cling film to wrap pastry

SOQL query WHERE filter by specific months

As a GM, is it bad form to ask for a moment to think when improvising?

Why did the Apollo 13 crew extend the LM landing gear?

Why do these characters still seem to be the same age after the events of Endgame?

Has the United States ever had a non-Christian President?

Why didn't this character get a funeral at the end of Avengers: Endgame?

Correct way of drawing empty, half-filled and fully filled circles?

How can I get people to remember my character's gender?



How to toggle mathematical operator and store calculations in a loop?


calculate math expression from a string using evalHow do I loop through or enumerate a JavaScript object?How do I break out of nested loops in Java?How to break out of jQuery each LoopReference — What does this symbol mean in PHP?How to toggle a boolean?Reference - What does this error mean in PHP?How do I determine whether my calculation of pi is accurate?Ways to iterate over a list in JavaSolving Math Expression in loops and storing in a dataframe with RCalculation in a loop in R






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-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"
]









share|improve this question
























  • Not entirely sure I understood. Your desired output is 6-1 or 5?

    – Javier Larroulet
    Mar 23 at 1:49

















-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"
]









share|improve this question
























  • Not entirely sure I understood. Your desired output is 6-1 or 5?

    – Javier Larroulet
    Mar 23 at 1:49













-1












-1








-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"
]









share|improve this question
















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"
]






php loops math toggle formula






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 21:41









mickmackusa

24k103860




24k103860










asked Mar 23 at 1:42









zarpiozarpio

2,18222733




2,18222733












  • Not entirely sure I understood. Your desired output is 6-1 or 5?

    – Javier Larroulet
    Mar 23 at 1:49

















  • Not entirely sure I understood. Your desired output is 6-1 or 5?

    – Javier Larroulet
    Mar 23 at 1:49
















Not entirely sure I understood. Your desired output is 6-1 or 5?

– Javier Larroulet
Mar 23 at 1:49





Not entirely sure I understood. Your desired output is 6-1 or 5?

– Javier Larroulet
Mar 23 at 1:49












2 Answers
2






active

oldest

votes


















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






share|improve this answer






























    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.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55309822%2fhow-to-toggle-mathematical-operator-and-store-calculations-in-a-loop%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      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






      share|improve this answer



























        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






        share|improve this answer

























          3












          3








          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






          share|improve this answer













          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







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 23 at 1:49









          NickNick

          43.5k142444




          43.5k142444























              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.






              share|improve this answer





























                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.






                share|improve this answer



























                  1












                  1








                  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.






                  share|improve this answer















                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 25 at 22:44

























                  answered Mar 23 at 21:36









                  mickmackusamickmackusa

                  24k103860




                  24k103860



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55309822%2fhow-to-toggle-mathematical-operator-and-store-calculations-in-a-loop%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현