Hello all,
I needed some help writing a code for one of my classes so I registered and became a member. 🙂

Goal:
I'm trying to write a code that will average a series of numbers generated by a user using a HTML text input form.

Requirements:

  • Must take an exact average

  • Must be able to add unlimited variables

HTML Code:

<html>

<Title>
Calculating an Average
</Title>

<head>
<h2>Calculate an Average</h2>
</head>

<body>
With this simple averaging calculator.


<form ACTION="test.php" METHOD="POST">
Input number series (separate by commas):<br></br>
<input type="text" name="avg"></input>
<br></br>

<input type="submit" value="Calculate"></input>


</form>


</body>
</html>

PHP Code:

<html>
<head>
</head>
<body>

<?php

/*
$avg=array (43, 24, 56, 76);
$count=count($avg, COUNT_NORMAL);
Print $count;
*/

function findAvg($val1,$val2,$val3,$val4){
	$avg=array ($val1,$val2,$val3,$val4);
	$count=count($avg, COUNT_NORMAL);
	$average=array_sum($avg)/$count;
	print $average;
}

findAvg(43, 24, 56, 76);
//findAvg($_POST[avg]);



//echo $avg{2};




?>
</body>
</html>

Note: This code works! But it's not editable by a user with the HTML page.

Problems:
I'm running into an issue with the POST function. It seems like whenever I throw in some variables while I am using findAvg("$POST[avg]"); it recognizes it as either (a) a boolean or (b) one variable, because my output is always 1 or an error.

Possible Solutions?:
Is it possible to create a ranged value for an array?
Is there a different _POST method for arrays?

Thanks! Any help will be much appreciated!

    Welcome to PHPBuilder!

    sk00ter;10988806 wrote:

    This code works!

    Er, well I guess that depends on your definition of "works." For example, I'd say it doesn't work because it requires exactly 4 parameters, so it's really more of a "FindAvg4" function (e.g. tailored for a specific use case).

    For it to "work," I'd rather see a more generic 'findAvg' function that takes a variable number of arguments and still works, e.g.:

    function findAvg()
    {
        return array_sum(func_get_args()) / func_num_args();
    }
    sk00ter;10988806 wrote:

    I'm running into an issue with the POST function.

    There is no such function; perhaps you meant the $POST array?

    sk00ter;10988806 wrote:

    It seems like whenever I throw in some variables while I am using findAvg("$_POST[avg]"); it recognizes it as either (a) a boolean or (b) one variable, because my output is always 1 or an error.

    Well PHP is deterministic, so it's going to be consistent. However, your example function call only passes one argument, whereas your findAvg() function is expecting four arguments.

    If you're wanting to take a string of characters (such as "1,2,3,4") and chop that string up into pieces using some separator (such as a comma), consider using a function such as [man]explode/man.

      You code works:

      function findAvg()
      {
          return array_sum(func_get_args()) / func_num_args();
      } 
      
      echo findAvg (1,2,3);

      And yes, I meant $POST, as in, getting information from a form in the HTML page I created.
      How would I insert a $
      POST as an argument for the findAvg correctly?
      I still get a output of "1" when using echo findAvg ("$_POST[avg]"), where [avg] is the name of my input form.

      Should I use the explode () function on the $_POST?

        sk00ter;10988817 wrote:

        How would I insert a $POST as an argument for the findAvg correctly?

        That would depend what "correctly" is supposed to mean. As it stands, your function expects four scalar inputs; $POST['avg'] is only one... hence why I offered the reference to [man]explode/man.

        However, perhaps even a better interface for the functionality would be to offer four separate inputs in the HTML form. It all depends on what you're trying to accomplish.

        sk00ter;10988817 wrote:

        I still get a output of "1" when using echo findAvg ("$_POST[avg]"), where [avg] is the name of my input form.

        Well what value did you supply for the 'avg' element in the form when you were testing it?

        Also note that your findAvg() function above doesn't return anything, so you really shouldn't be trying to echo its (nonexistent) return value.

        sk00ter;10988817 wrote:

        Should I use the explode () function on the $POST?

        Again, that's up to you. However, I'm guessing you mean a specific item in the POST'ed data, as using [man]explode/man on an array like $POST itself doesn't make any sense.

        Either way, you either need to a) manipulate the received data into the format that your findAvg() expects, or b) change the way your findAvg() function expects data.

          bradgrafelman;10988819 wrote:

          That would depend what "correctly" is supposed to mean.

          Well I kept getting a value output of "1" so I was assuming it was done incorrectly.

          bradgrafelman;10988819 wrote:

          However, perhaps even a better interface for the functionality would be to offer four separate inputs in the HTML form. It all depends on what you're trying to accomplish.

          I'd like to be able to add an unlimited amount of inputs, rather than restricting it to 3 or 4.

          bradgrafelman;10988819 wrote:

          Well what value did you supply for the 'avg' element in the form when you were testing it?

          A random series of numbers separated by commas like so: 34,54,76,78,32

          bradgrafelman;10988819 wrote:

          using explode() on an array like $_POST itself doesn't make any sense.

          I agree, it simply doesn't work. Found that out through trial/error.

          bradgrafelman;10988819 wrote:

          Either way, you either need to a) manipulate the received data into the format that your findAvg() expects, or b) change the way your findAvg() function expects data.

          A) Apart from making several POST forms, is there any way to separate input data in a single field?
          😎 Can I somehow manipulate a $_POST value to be read as multiple inputs of integers rather than a single array so it can be understood by the findAvg() function?

          From what you're saying, it sounds like it is impossible for $_POSTs to carry multiples of input data like a series of numbers: 34,54,65,78
          PHP just recognizes this data as the whole, boolean phrase rather than a series of variables. Thus, the output is always "1".

          While you did re-write my code, it didn't really change the functionality. Your code and my code are still limited by the $POST value, at least, by a single one. Using multiple $POSTs will work, but that's not what I'm trying to do. Once again I'm attempting to write a code that lets a user put in an unlimited amount of inputs(variables, arguments) for the findAvg() function through a POST element within a HTML page.

          If this is impossible, I will just settle with several POST elements in my HTML, unless there is someway to break up data through PHP in a single HTML POST element.

            A) Apart from making several POST forms, is there any way to separate input data in a single field?

            He already told you this explode() would seperate a single input into an array. You could then count how many items are in the array via sizeof() Then create a loop using foreach that adds each element to a sum, and divide by the number of elements.

            Basic example as follows:

            //Given input from single form input
            $input = '12,27,15,85,33,71,49';
            
            // put the numbers into an array
            $nums = explode(',',$input);
            
            // initialize the total variable
            $total = 0;
            
            // Add each number to the total
            foreach($nums as $num) {
               $total += $num;
            }
            
            // Echo the average
            echo $total/sizeof($nums);
            
              sk00ter;10988824 wrote:

              I'd like to be able to add an unlimited amount of inputs, rather than restricting it to 3 or 4.

              In that case, you might consider two modifications:

              1. A change to findAvg() similar to what I mentioned above, where the function is able to handle an arbitrary number of arguments.

              2. A change to your form... create multiple text boxes all with the name "numbers[]" (or whatever - the key is the '[]' at the end of the name).

                That way, $_POST['numbers'] will actually become an array itself... e.g. one that you could simply pass directly to your (new and improved) findAvg() function. EDIT: Woops, wasn't thinking... you can't just pass it directly (since my function above still expects each input to be an argument in the function call); however, it's still a one-liner thanks to the function [man]call_user_func_array/man.

                You could even use a touch of Javascript and include an "Add New Input" button that allows the user to create as many textboxes as they want.

              sk00ter;10988824 wrote:

              I agree, it simply doesn't work. Found that out through trial/error.

              But it never should have even come to trial and error. [man]explode/man takes a single string and 'explodes' it into a bunch of pieces (array elements, in other words). $_POST is already an array containing all variables/entities that were POST'ed.

              sk00ter;10988824 wrote:

              A) Apart from making several POST forms, is there any way to separate input data in a single field?
              😎 Can I somehow manipulate a $_POST value to be read as multiple inputs of integers rather than a single array so it can be understood by the findAvg() function?

              Yes to both - [man]explode/man is one possible answer (as Derokorian further points out above).

              sk00ter;10988824 wrote:

              From what you're saying, it sounds like it is impossible for $_POSTs to carry multiples of input data like a series of numbers: 34,54,65,78

              Of course it's possible... but that data isn't a "series of numbers" but rather just a plain old character string. And yes, POST'ed data is just a bunch of strings identified by some key or name (e.g. the form element's name).

              sk00ter;10988824 wrote:

              PHP just recognizes this data as the whole, boolean phrase rather than a series of variables.

              Er... no, PHP doesn't "recognize" anything. Garbage in, garbage out - PHP just sees a bunch of string data that was POST'ed to it, so that's all it stores in $_POST['avg'] - just a plain old string.

              And besides, how is "34,54,65,78" a "boolean phrase" in any way?

              sk00ter;10988824 wrote:

              Thus, the output is always "1".

              Nope... at least, not for me. What you're doing here:

              findAvg($_POST['avg']);

              is the same as:

              findAvg('34,54,65,78');

              which is going to produce output like:

              Warning: Missing argument 2 for findAvg()
              
              Warning: Missing argument 3 for findAvg()
              
              Warning: Missing argument 4 for findAvg()
              
              Notice: Undefined variable: val2
              
              Notice: Undefined variable: val3
              
              Notice: Undefined variable: val4
              8.5

              with the '8.5' being the expected result (34/4 = 8.5)... as well as the PHP error messages (since you aren't calling the function with the proper number of arguments).

              sk00ter;10988824 wrote:

              While you did re-write my code, it didn't really change the functionality.

              I suppose nothing changed the functionality... other than the fact that my version is functional and yours is nonfunctional for any number of inputs other than 4.... but yeah, other than that... 😉

              sk00ter;10988824 wrote:

              Your code and my code are still limited by the $POST value, at least, by a single one.

              Actually no, neither of our functions are "limited" in any way by any $POST value. If you don't believe me, take a look at my version again:

              function findAvg() 
              { 
                  return array_sum(func_get_args()) / func_num_args(); 
              } 

              and point out where $_POST appears in the code and/or has any direct correlation.

              sk00ter;10988824 wrote:

              Using multiple $_POSTs will work, but that's not what I'm trying to do. Once again I'm attempting to write a code that lets a user put in an unlimited amount of inputs(variables, arguments) for the findAvg() function through a POST element within a HTML page.

              Well for one, if that truly is your goal then you're going to need to change the findAvg() function as alraeady stated above. Otherwise, it will produce incorrect results for any number of inputs other than 4.

              Second, it's not that you need "multiple $_POSTs", just multiple somethings. Whether you use multiple form entities with different names, multiple entities with a shared name like 'numbers[]', or a single form entity whose string data gets processed into multiple pieces (again, such as using [man]explode/man)... etc.

              Derokorian;10988826 wrote:

              Basic example as follows:

              //Given input from single form input
              $input = '12,27,15,85,33,71,49';
              
              // put the numbers into an array
              $nums = explode(',',$input);
              
              // initialize the total variable
              $total = 0;
              
              // Add each number to the total
              foreach($nums as $num) {
                 $total += $num;
              }
              
              // Echo the average
              echo $total/sizeof($nums);
              

              Aye, basic 'nuff, although I'd personally stick with the use of array_sum() for its conciseness:

              //Given input from single form input
              $input = '12,27,15,85,33,71,49';
              
              // put the numbers into an array
              $nums = explode(',',$input);
              
              // Echo the average
              echo array_sum($nums)/sizeof($nums);
              

                Aye - I always forget about array_sum, mainly because I never use it lol.

                  OK, yes, all this stuff works. However, could you show me the input form side of things? I already know how to write the algorithm to calculate the average. The input form is what I'm trying to troubleshoot now.

                    Based on which input method... your current one? In other words, you present the user with a single text box and expect them to submit a comma-separated list of numbers?

                    If so, we've already told you (a few times, actually) how to do that; [man]explode/man the string to get an array, and pass the pieces of that array as individual arguments (since that's what your findAvg() function expects). If you get stuck, post whatever code you came up with so we can see where you went wrong or what you're missing.

                      bradgrafelman;10988867 wrote:

                      Based on which input method... your current one? In other words, you present the user with a single text box and expect them to submit a comma-separated list of numbers?

                      If so, we've already told you (a few times, actually) how to do that; [man]explode/man the string to get an array, and pass the pieces of that array as individual arguments (since that's what your findAvg() function expects). If you get stuck, post whatever code you came up with so we can see where you went wrong or what you're missing.

                      Please read my first post. The input must come from a separate HTML page using the POST method in a form element.

                      It's one thing to add numbers to a variable and use explode, but it becomes entirely different when your array string comes from a $_POST method from a form in a separate HTML page like the one I posted in my OP.

                      when you:

                      function findAvg(){
                      	return array_sum(func_get_args()) / func_num_args();
                      }
                      
                      $post = "$_POST[avg]";
                      $explode=explode(",",$post);
                      
                      print "$post<br></br>";
                      print "$explode<br></br>";
                      
                      echo findAvg($post);
                      echo findAvg($explode);
                      

                      It does not work. It returns this when the input from the text field on the form element using the POST method is "45,69,23":

                      45,69,23
                      
                      Array
                      
                      45
                      
                      
                      

                      The $post variable gives the input
                      The explode function just gives an "Array"
                      findAvg($post) just gives the first of the numbers
                      And findAvg($explode) gives the output of "0"

                      Here is my INPUT form on the separate page:

                      <form ACTION="newAverageAlgo.php" METHOD="POST">
                      Input number series (separate by commas):<br></br>
                      <input type="text" size="45" name="avg"></input>
                      <br></br>
                      <input type="submit" value="Calculate"></input>
                      </form>
                      

                      Am I missing something here? Or does this just not work.

                        sk00ter;10988873 wrote:

                        Please read my first post. The input must come from a separate HTML page using the POST method in a form element.

                        Right, that's exactly what I described above.

                        sk00ter;10988873 wrote:

                        It's one thing to add numbers to a variable and use explode, but it becomes entirely different when your array string comes from a $POST method from a form in a separate HTML page like the one I posted in my OP.

                        Two things:

                        1. No, it's not "entirely different." You take a string, you explode() it on some delimiting character, and you get a bunch of individual pieces back. Same concept whether it's Derokorian's example or some data POST'ed in a form.

                        2. The phrase "$_POST method" doesn't make much sense; POST is the method, $_POST is simply an array of data.

                        sk00ter;10988873 wrote:

                        The explode function just gives an "Array"

                        ...which is exactly what it's supposed to do. The manual page for [man]explode/man clearly states that the function returns an [man]array[/man] (which is a complex data type, not something you can just "print" without getting something meaningless like the word "Array").

                        sk00ter;10988873 wrote:

                        findAvg($post) just gives the first of the numbers

                        Yes, that's because "45,69,23" isn't a number, it's a string. As such, when PHP tries to use it as a number (such as in arithmetic), it casts that string to a numeric type (which will stop at the first non-numeric character, making that string equivalent to the number 45).

                        sk00ter;10988873 wrote:

                        And findAvg($explode) gives the output of "0"

                        Same problem as above - your function expects numbers, yet you're passing it a non-numeric type (an array).

                        If you want to use the items in an array as individual parameters in a function call, that's where [man]call_user_func_array/man can help, e.g.:

                        call_user_func_array('function_name', $array_of_arguments);

                        will call function 'function_name' with the first parameter set to $array_of_arguments[0], the second set to $array_of_arguments[1], etc. for all items in the array.

                          bradgrafelman;10988875 wrote:

                          If you want to use the items in an array as individual parameters in a function call, that's where [man]call_user_func_array/man can help, e.g.:

                          call_user_func_array('function_name', $array_of_arguments);

                          will call function 'function_name' with the first parameter set to $array_of_arguments[0], the second set to $array_of_arguments[1], etc. for all items in the array.

                          While you two seem entirely too nit-picky at the way I describe elements in PHP, this was the missing code I needed. I knew about the explode() function and the count() function from class, so I obviously tried using those first. However, I am still a PHP newbie so at least you guys have shown me 3 new functions.

                          Thanks a lot!

                          My Averaging Function:

                          function findAvg(){
                          	return array_sum(func_get_args()) / func_num_args();
                          }
                          
                          $post = "$_POST[avg]";
                          $explode=explode(",",$post);
                          $call=call_user_func_array('findAvg', $explode); 
                          
                          print $call;
                          
                            sk00ter;10988877 wrote:

                            While you two seem entirely too nit-picky at the way I describe elements

                            They really aren't. If something is a method, you call it a method, if it's an array you call it an array if you want others to understand you.

                            When it comes to writing code, if you try using an array like a method, you will get parse errors.

                            When it comes to communication with other programmers, if you call an array a method, people will either believe it's a method or believe that you believe it's a method, or at the very best that you're simply confused about what's what. This means that they might not be able to help you, if that's your goal, or that they will correct you so that you understand how things work. And if you really do understand how things work, then using the correct terminology is the key to letting others know that.

                            Also do note that while $POST is initially an array, you can actually turn it into a function object (although doing so is not necessarily a good idea) and from that point on call it like you would any other function

                            $_POST('function', 'args');
                            
                              Write a Reply...