0

I need to create a text field that can get multiple input like this...

1, 2, 3, 4

Then the output should be...

Number of input: 4

Mean: 2.5

The problem is how can I count the number of the input, I mean how the program know that how many input that user type into the text field, and use each value to calculate a summation for all. Does anybody has any methods or any idea?

Thanks.

sjagr
  • 15,983
  • 5
  • 40
  • 67
wendy
  • 1

2 Answers2

0

Use explode(); and explode all the commas (,). That will give you an array.

From there, use count and a loop for counting and get the mean. Use trim() aswel for getting rid of empty spaces.

Zander
  • 1,076
  • 1
  • 9
  • 23
0

You can test the code here: http://writecodeonline.com/php/

$input = "1, 2, 3, 4";

//remove all whitespace
$input = str_replace(' ', '', $input); 

//turn the string into an array of integers
$numbers= array_map('intval', explode(',', $input)); 

//the number of elements
$count = count( $numbers );

//sum the numbers
$sum = array_sum( $numbers );

//print the number of inputs, a new line character, and the mean
echo "Number of inputs: $count\r\n"; 
echo 'Mean: ' . $sum / $count; 
Kacy
  • 3,330
  • 4
  • 29
  • 57