在一个文本字段中计算和读取多个输入

时间:2015-02-09 16:50:34

标签: php input textfield

我需要创建一个可以获得多个输入的文本字段......

  

1,2,3,4

然后输出应该是......

  

输入数量:4

     

平均值:2.5

问题是如何计算输入的数量,我的意思是程序如何知道用户在文本字段中键入了多少输入,并使用每个值来计算所有的总和。有没有人有任何方法或想法?

感谢。

2 个答案:

答案 0 :(得分:0)

使用explode();并展开所有逗号(,)。那会给你一个数组。

从那里,使用计数和循环进行计数并获得平均值。使用trim() aswel来消除空白区域。

答案 1 :(得分:0)

您可以在此处测试代码: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;