PHP array: Conditional sum












0















I have a an array looking like this:



$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);


I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:



$newarray = array("a" => 3, "b" => 5);


I have tried using a foreach() loop within another foreach() loop like this:



foreach ($xml->children() as $output) {
foreach ($array as $key => $value) {
if (substr($key,0,1) == $output->KEY) {
$sum += $value; echo $sum;
}
}
}


It didn't work as the results apparently added the prior calculations.










share|improve this question





























    0















    I have a an array looking like this:



    $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);


    I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:



    $newarray = array("a" => 3, "b" => 5);


    I have tried using a foreach() loop within another foreach() loop like this:



    foreach ($xml->children() as $output) {
    foreach ($array as $key => $value) {
    if (substr($key,0,1) == $output->KEY) {
    $sum += $value; echo $sum;
    }
    }
    }


    It didn't work as the results apparently added the prior calculations.










    share|improve this question



























      0












      0








      0








      I have a an array looking like this:



      $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);


      I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:



      $newarray = array("a" => 3, "b" => 5);


      I have tried using a foreach() loop within another foreach() loop like this:



      foreach ($xml->children() as $output) {
      foreach ($array as $key => $value) {
      if (substr($key,0,1) == $output->KEY) {
      $sum += $value; echo $sum;
      }
      }
      }


      It didn't work as the results apparently added the prior calculations.










      share|improve this question
















      I have a an array looking like this:



      $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);


      I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:



      $newarray = array("a" => 3, "b" => 5);


      I have tried using a foreach() loop within another foreach() loop like this:



      foreach ($xml->children() as $output) {
      foreach ($array as $key => $value) {
      if (substr($key,0,1) == $output->KEY) {
      $sum += $value; echo $sum;
      }
      }
      }


      It didn't work as the results apparently added the prior calculations.







      php arrays calculation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 3 at 2:40









      Alive to Die

      56k83273




      56k83273










      asked Jan 2 at 13:52









      McClaudLiveMcClaudLive

      186




      186
























          5 Answers
          5






          active

          oldest

          votes


















          1














          You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.



          <?php
          $sum = ;
          foreach ($array as $key => $value) {
          $letter = substr($key,0,1);
          if (!isset($sum[$letter])){$sum[$letter] = 0;}
          $sum[$letter] += $value;
          }

          var_dump($sum);





          share|improve this answer



















          • 1





            @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

            – G4Hu
            Jan 2 at 14:10








          • 2





            Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

            – JohnnyB1988
            Jan 2 at 14:10



















          2














          Simple solution:



          $final_array=;
          foreach($array as $key=>$value){
          $final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
          }
          print_r($final_array);


          Output:- https://3v4l.org/tZ4Ei






          share|improve this answer

































            1














            A simple isset should do it:



            $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
            $result = array();
            foreach ($array as $oldkey => $val) {
            $newkey = substr($oldkey, 0, 1);
            if (isset($result[$newkey]) === false)
            $result[$newkey] = $val;
            else
            $result[$newkey] += $val;
            }
            var_dump($result);





            share|improve this answer


























            • Damn it :D Just few seconds later

              – JohnnyB1988
              Jan 2 at 13:59











            • @JohnnyB1988 To be precise two seconds later.

              – CodeIt
              Jan 2 at 14:18













            • @Salman I'm glad that my code is like yours, it means that my studies is on good way.

              – JohnnyB1988
              Jan 2 at 14:21



















            1














            Try this way



            $array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
            $result = array();
            foreach($array as $key => $value){
            if(isset($result[$key[0]])){
            $result[$key[0]] = $result[$key[0]]+$value;
            } else {
            $result[$key[0]] = $value;
            }
            }
            print_r($result);





            share|improve this answer





















            • 1





              You have a missing ) in your condition

              – executable
              Jan 2 at 14:03



















            0














            Quick and Easy, you can have any number of numbers in the array after the characters.



            <?php

            $array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
            $newArray = ;

            foreach ($array as $key => $value) {
            $key = preg_replace("/[0-9]*$/", "", $key);
            $newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
            }

            print_r($newArray);





            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%2f54007565%2fphp-array-conditional-sum%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.



              <?php
              $sum = ;
              foreach ($array as $key => $value) {
              $letter = substr($key,0,1);
              if (!isset($sum[$letter])){$sum[$letter] = 0;}
              $sum[$letter] += $value;
              }

              var_dump($sum);





              share|improve this answer



















              • 1





                @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

                – G4Hu
                Jan 2 at 14:10








              • 2





                Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

                – JohnnyB1988
                Jan 2 at 14:10
















              1














              You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.



              <?php
              $sum = ;
              foreach ($array as $key => $value) {
              $letter = substr($key,0,1);
              if (!isset($sum[$letter])){$sum[$letter] = 0;}
              $sum[$letter] += $value;
              }

              var_dump($sum);





              share|improve this answer



















              • 1





                @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

                – G4Hu
                Jan 2 at 14:10








              • 2





                Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

                – JohnnyB1988
                Jan 2 at 14:10














              1












              1








              1







              You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.



              <?php
              $sum = ;
              foreach ($array as $key => $value) {
              $letter = substr($key,0,1);
              if (!isset($sum[$letter])){$sum[$letter] = 0;}
              $sum[$letter] += $value;
              }

              var_dump($sum);





              share|improve this answer













              You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.



              <?php
              $sum = ;
              foreach ($array as $key => $value) {
              $letter = substr($key,0,1);
              if (!isset($sum[$letter])){$sum[$letter] = 0;}
              $sum[$letter] += $value;
              }

              var_dump($sum);






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jan 2 at 13:58









              JohnnyB1988JohnnyB1988

              1467




              1467








              • 1





                @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

                – G4Hu
                Jan 2 at 14:10








              • 2





                Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

                – JohnnyB1988
                Jan 2 at 14:10














              • 1





                @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

                – G4Hu
                Jan 2 at 14:10








              • 2





                Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

                – JohnnyB1988
                Jan 2 at 14:10








              1




              1





              @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

              – G4Hu
              Jan 2 at 14:10







              @executable only the first character needs to be considered for OP. Even if $key = 'ab'; this would result in $letter = 'a'; since substr($key, 0, 1) return the first character

              – G4Hu
              Jan 2 at 14:10






              2




              2





              Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

              – JohnnyB1988
              Jan 2 at 14:10





              Author asked just with first character " sum values foreach "unique" key when only the first character is considered" You can also validate key with ctype_alpha to check if it is letter, or number and by that result make additional decisions

              – JohnnyB1988
              Jan 2 at 14:10













              2














              Simple solution:



              $final_array=;
              foreach($array as $key=>$value){
              $final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
              }
              print_r($final_array);


              Output:- https://3v4l.org/tZ4Ei






              share|improve this answer






























                2














                Simple solution:



                $final_array=;
                foreach($array as $key=>$value){
                $final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
                }
                print_r($final_array);


                Output:- https://3v4l.org/tZ4Ei






                share|improve this answer




























                  2












                  2








                  2







                  Simple solution:



                  $final_array=;
                  foreach($array as $key=>$value){
                  $final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
                  }
                  print_r($final_array);


                  Output:- https://3v4l.org/tZ4Ei






                  share|improve this answer















                  Simple solution:



                  $final_array=;
                  foreach($array as $key=>$value){
                  $final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
                  }
                  print_r($final_array);


                  Output:- https://3v4l.org/tZ4Ei







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 3 at 8:29

























                  answered Jan 2 at 14:11









                  Alive to DieAlive to Die

                  56k83273




                  56k83273























                      1














                      A simple isset should do it:



                      $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
                      $result = array();
                      foreach ($array as $oldkey => $val) {
                      $newkey = substr($oldkey, 0, 1);
                      if (isset($result[$newkey]) === false)
                      $result[$newkey] = $val;
                      else
                      $result[$newkey] += $val;
                      }
                      var_dump($result);





                      share|improve this answer


























                      • Damn it :D Just few seconds later

                        – JohnnyB1988
                        Jan 2 at 13:59











                      • @JohnnyB1988 To be precise two seconds later.

                        – CodeIt
                        Jan 2 at 14:18













                      • @Salman I'm glad that my code is like yours, it means that my studies is on good way.

                        – JohnnyB1988
                        Jan 2 at 14:21
















                      1














                      A simple isset should do it:



                      $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
                      $result = array();
                      foreach ($array as $oldkey => $val) {
                      $newkey = substr($oldkey, 0, 1);
                      if (isset($result[$newkey]) === false)
                      $result[$newkey] = $val;
                      else
                      $result[$newkey] += $val;
                      }
                      var_dump($result);





                      share|improve this answer


























                      • Damn it :D Just few seconds later

                        – JohnnyB1988
                        Jan 2 at 13:59











                      • @JohnnyB1988 To be precise two seconds later.

                        – CodeIt
                        Jan 2 at 14:18













                      • @Salman I'm glad that my code is like yours, it means that my studies is on good way.

                        – JohnnyB1988
                        Jan 2 at 14:21














                      1












                      1








                      1







                      A simple isset should do it:



                      $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
                      $result = array();
                      foreach ($array as $oldkey => $val) {
                      $newkey = substr($oldkey, 0, 1);
                      if (isset($result[$newkey]) === false)
                      $result[$newkey] = $val;
                      else
                      $result[$newkey] += $val;
                      }
                      var_dump($result);





                      share|improve this answer















                      A simple isset should do it:



                      $array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
                      $result = array();
                      foreach ($array as $oldkey => $val) {
                      $newkey = substr($oldkey, 0, 1);
                      if (isset($result[$newkey]) === false)
                      $result[$newkey] = $val;
                      else
                      $result[$newkey] += $val;
                      }
                      var_dump($result);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 2 at 14:00

























                      answered Jan 2 at 13:58









                      Salman ASalman A

                      184k67343441




                      184k67343441













                      • Damn it :D Just few seconds later

                        – JohnnyB1988
                        Jan 2 at 13:59











                      • @JohnnyB1988 To be precise two seconds later.

                        – CodeIt
                        Jan 2 at 14:18













                      • @Salman I'm glad that my code is like yours, it means that my studies is on good way.

                        – JohnnyB1988
                        Jan 2 at 14:21



















                      • Damn it :D Just few seconds later

                        – JohnnyB1988
                        Jan 2 at 13:59











                      • @JohnnyB1988 To be precise two seconds later.

                        – CodeIt
                        Jan 2 at 14:18













                      • @Salman I'm glad that my code is like yours, it means that my studies is on good way.

                        – JohnnyB1988
                        Jan 2 at 14:21

















                      Damn it :D Just few seconds later

                      – JohnnyB1988
                      Jan 2 at 13:59





                      Damn it :D Just few seconds later

                      – JohnnyB1988
                      Jan 2 at 13:59













                      @JohnnyB1988 To be precise two seconds later.

                      – CodeIt
                      Jan 2 at 14:18







                      @JohnnyB1988 To be precise two seconds later.

                      – CodeIt
                      Jan 2 at 14:18















                      @Salman I'm glad that my code is like yours, it means that my studies is on good way.

                      – JohnnyB1988
                      Jan 2 at 14:21





                      @Salman I'm glad that my code is like yours, it means that my studies is on good way.

                      – JohnnyB1988
                      Jan 2 at 14:21











                      1














                      Try this way



                      $array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
                      $result = array();
                      foreach($array as $key => $value){
                      if(isset($result[$key[0]])){
                      $result[$key[0]] = $result[$key[0]]+$value;
                      } else {
                      $result[$key[0]] = $value;
                      }
                      }
                      print_r($result);





                      share|improve this answer





















                      • 1





                        You have a missing ) in your condition

                        – executable
                        Jan 2 at 14:03
















                      1














                      Try this way



                      $array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
                      $result = array();
                      foreach($array as $key => $value){
                      if(isset($result[$key[0]])){
                      $result[$key[0]] = $result[$key[0]]+$value;
                      } else {
                      $result[$key[0]] = $value;
                      }
                      }
                      print_r($result);





                      share|improve this answer





















                      • 1





                        You have a missing ) in your condition

                        – executable
                        Jan 2 at 14:03














                      1












                      1








                      1







                      Try this way



                      $array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
                      $result = array();
                      foreach($array as $key => $value){
                      if(isset($result[$key[0]])){
                      $result[$key[0]] = $result[$key[0]]+$value;
                      } else {
                      $result[$key[0]] = $value;
                      }
                      }
                      print_r($result);





                      share|improve this answer















                      Try this way



                      $array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
                      $result = array();
                      foreach($array as $key => $value){
                      if(isset($result[$key[0]])){
                      $result[$key[0]] = $result[$key[0]]+$value;
                      } else {
                      $result[$key[0]] = $value;
                      }
                      }
                      print_r($result);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 2 at 14:46









                      executable

                      1,9452924




                      1,9452924










                      answered Jan 2 at 14:00









                      TamimTamim

                      320511




                      320511








                      • 1





                        You have a missing ) in your condition

                        – executable
                        Jan 2 at 14:03














                      • 1





                        You have a missing ) in your condition

                        – executable
                        Jan 2 at 14:03








                      1




                      1





                      You have a missing ) in your condition

                      – executable
                      Jan 2 at 14:03





                      You have a missing ) in your condition

                      – executable
                      Jan 2 at 14:03











                      0














                      Quick and Easy, you can have any number of numbers in the array after the characters.



                      <?php

                      $array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
                      $newArray = ;

                      foreach ($array as $key => $value) {
                      $key = preg_replace("/[0-9]*$/", "", $key);
                      $newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
                      }

                      print_r($newArray);





                      share|improve this answer




























                        0














                        Quick and Easy, you can have any number of numbers in the array after the characters.



                        <?php

                        $array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
                        $newArray = ;

                        foreach ($array as $key => $value) {
                        $key = preg_replace("/[0-9]*$/", "", $key);
                        $newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
                        }

                        print_r($newArray);





                        share|improve this answer


























                          0












                          0








                          0







                          Quick and Easy, you can have any number of numbers in the array after the characters.



                          <?php

                          $array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
                          $newArray = ;

                          foreach ($array as $key => $value) {
                          $key = preg_replace("/[0-9]*$/", "", $key);
                          $newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
                          }

                          print_r($newArray);





                          share|improve this answer













                          Quick and Easy, you can have any number of numbers in the array after the characters.



                          <?php

                          $array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
                          $newArray = ;

                          foreach ($array as $key => $value) {
                          $key = preg_replace("/[0-9]*$/", "", $key);
                          $newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
                          }

                          print_r($newArray);






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 2 at 14:03









                          AnugaAnuga

                          1,069719




                          1,069719






























                              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%2f54007565%2fphp-array-conditional-sum%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

                              android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                              SQL update select statement

                              'app-layout' is not a known element: how to share Component with different Modules