Page 1 of 2 12 LastLast
Results 1 to 10 of 18

Thread: Adding values in single variable

  1. #1
    Join Date
    Jul 2012
    Posts
    197
    Thanks
    55
    Thanked 3 Times in 3 Posts

    Default Adding values in single variable

    $variable = 123 ;
    ? best method to retrieve the sum of the $variable as Eg - 1+2+3 = 6
    You will know the truth, and the truth will set you free (John 8:32)(The truth is about the only begotten son of GOD.....When you feel you are alone for facing your problems, God will never leave you by your own You are important for God

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,926
    Thanks
    43
    Thanked 3,192 Times in 3,155 Posts
    Blog Entries
    12

    Default

    I don't know if this is the best way. It is one way:

    PHP Code:
    <?php
    $variable 
    123;
    $va str_split($variable);
    $result 0;
    foreach (
    $va as $v){
        
    $result += $v;
    }
    echo 
    $result;
    ?>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    That would work (and for some reason it's appealing to me because I like foreach).
    The best way would be to start with another kind of input (like an array).

    The most efficient way* is as follows:
    PHP Code:
    $n 123;
    $o=0;
    for(
    $i=0;$i+1<strlen($n);$i++) {
       
    $o+=$n[$i];
    }
    echo 
    $o//5 
    This uses a trick where it treats this number as a string (technically, to not rely on a trick, you could convert it first), then it treats that string as an array of characters.


    (*I'm talking about the shortest code to do this. For the most efficient machine processing, it's probably with while, imitating the for-loop, as you taught me a long time ago, John. You could obviously convert this one if you want.)
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,926
    Thanks
    43
    Thanked 3,192 Times in 3,155 Posts
    Blog Entries
    12

    Default

    The trick doesn't work here. I get 0, and the correct result is 6 not 5, so you probably didn't try it out. Or if you did and got 5, it still doesn't work. This works:

    PHP Code:
    <?php
    $variable 
    123;
    $va str_split($variable);
    $result 0;
    $c count($va);
    while (--
    $c > -1){
        
    $result += $va[$c];
    }
    echo 
    $result;
    ?>
    What you're calling a trick is known as type conversion. Various languages will or will not do it. Of those that will some will do it in one sort of circumstance and not another, sometimes without any immediately obvious reason. Both of my snippets rely upon type conversion as well. First that a number will be treated as a string and be split into an array, and second that the now string representations of the individual numbers will be treated as numbers when added to $result. In both cases this appears to go along fine. In your code I'm not sure where it doesn't convert as expected, or even if the lack of an expected type conversion is the problem. But, I get no errors and the result here for that code is 0.

    Ah, if I type convert your $n:

    Code:
    $n = 123 . '';
    Then it does work and gives 5, which is wrong because here:

    Code:
    for($i=0;$i+1<strlen($n);$i++) {
    1 is added, which skips the first character/digit.

    So I guess your's might 'work' in some version of PHP if it type converts within the loop. Mine (PHP 5.3) doesn't. It gives a null or falsey value to each $n[$i] in the loop.

    It appears that, in my version of PHP at least, type conversion occurs number to string when an explicit string function is used upon a number, but not when a string convention ($str[$index]) is. String to number occurs in all of these, when they work, when using an arithmetic operator upon a string that can be a number.
    Last edited by jscheuer1; 10-28-2013 at 01:44 PM. Reason: played with it some more
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. The Following User Says Thank You to jscheuer1 For This Useful Post:

    djr33 (10-28-2013)

  6. #5
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    Sorry, I didn't test it. (And my math was off-- just quick in-my-head calculation... haha, I can't add.)
    Right, if you type convert it with the empty string, it works.

    I didn't realize that. I guess it's just slightly too much to use an integer as a string as an array. (Each conversion works independently though!)


    As for the loop, just play with it a bit-- subtract one, add one, whatever works best. (Indices start at 0, strlen() is the number of characters, and we want it to go to one less than that-- I don't think the middle argument is the problem.)


    If you can't figure it out I can check later. I'm just busy at the moment. This does work, in theory.


    As I said in my last post, I prefer the foreach method because I know exactly what is going on there intuitively and wouldn't end up with typos like this (But technically this method is more efficient.)
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  7. #6
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    PHP Code:
    <?php

    $i 
    123;
    $sum_of_digits array_sumstr_split$i ) );
    print 
    $sum_of_digits;  // 6

  8. The Following User Says Thank You to traq For This Useful Post:

    djr33 (10-29-2013)

  9. #7
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    Haha, that works. I wasn't even thinking about the sum, but about separating the digits. That's probably simplest. (Although at the most technical level, I don't know how efficient those functions are if speed is really the concern. I'm sure it would be fine. Addition isn't, in any way, very taxing on the system.)
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  10. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,926
    Thanks
    43
    Thanked 3,192 Times in 3,155 Posts
    Blog Entries
    12

    Default

    In javascript we are taught that, if there's an internal method of doing something (native function), it's almost always more efficient than doing it yourself using more basic functions. So I would vote for Adrian's method as probably best. Time trials would need to be used to know for sure.

    PHP Code:
    $variable 123;
    echo 
    array_sum(str_split($variable)); 
    Last edited by jscheuer1; 10-29-2013 at 05:54 PM. Reason: add code
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  11. #9
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by jscheuer1 View Post
    In javascript we are taught that, if there's an internal method of doing something (native function), it's almost always more efficient than doing it yourself using more basic functions.
    Which also holds true in PHP.

    Quote Originally Posted by jscheuer1 View Post
    Time trials would need to be used to know for sure.
    just for kicks:
    Averages of multiple 1,000-iteration trials:
    PHP Code:
    # my method

    $variable 123
    echo 
    array_sum(str_split($variable));  

    # 0.0032110214233398 sec 
    PHP Code:
    # John's second method

    $variable 123;
    $va str_split($variable);
    $result 0;
    $c count($va);
    while (--
    $c > -1){
        
    $result += $va[$c];
    }

    # 0.0034551620483398 sec 
    PHP Code:
    # John's first method

    $variable 123
    $va str_split($variable); 
    $result 0
    foreach (
    $va as $v){ 
        
    $result += $v


    # 0.0032589435577393 sec 
    ...but, as you see, not much difference in this particular case. Two milliseconds between the fastest and slowest methods isn't very much. And remember, that's for 1,000 iterations.

  12. The Following User Says Thank You to traq For This Useful Post:

    djr33 (10-30-2013)

  13. #10
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    Isn't that 2 tenths of a millisecond?

    Oddly enough, foreach is faster than while (or for) loops. I'm surprised. It's a sort of weird feature in PHP, but I love it. Now I like it more.


    In javascript we are taught that, if there's an internal method of doing something (native function), it's almost always more efficient than doing it yourself using more basic functions.[/quote]
    Which also holds true in PHP.[/quote]On average, and perhaps especially when PHP sometimes has default functions that are based in C++ (I think, and even if so I'm not sure which ones). But I'd imagine that sometimes it's overkill to use something-- for example, I imagined that foreach was a more complicated kind of loop. Here it turns out that particular example was wrong, of course. It was efficient.




    By the way, letom, have we answered your question? You now have a few versions to pick from so you can use whatever you want. If you need more help, feel free to ask
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

Similar Threads

  1. Replies: 1
    Last Post: 10-27-2010, 05:05 PM
  2. Replies: 3
    Last Post: 05-27-2008, 05:36 PM
  3. Replies: 2
    Last Post: 05-26-2008, 08:16 AM
  4. Replies: 3
    Last Post: 08-03-2007, 10:22 PM
  5. insert dynamic values into javascript variable
    By rich1234 in forum JavaScript
    Replies: 10
    Last Post: 07-29-2007, 10:02 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •