【发布时间】:2015-02-09 16:50:33
【问题描述】:
我需要创建一个可以像这样获取多个输入的文本字段...
1、2、3、4
那么输出应该是……
输入数量:4
平均值:2.5
问题是如何计算输入的数量,我的意思是程序如何知道用户在文本字段中输入了多少输入,并使用每个值来计算所有输入的总和。有没有人有什么方法或想法?
谢谢。
【问题讨论】:
-
explode()-count()
我需要创建一个可以像这样获取多个输入的文本字段...
1、2、3、4
那么输出应该是……
输入数量:4
平均值:2.5
问题是如何计算输入的数量,我的意思是程序如何知道用户在文本字段中输入了多少输入,并使用每个值来计算所有输入的总和。有没有人有什么方法或想法?
谢谢。
【问题讨论】:
explode() - count()
使用explode(); 并分解所有逗号 (,)。这会给你一个数组。
从那里,使用计数和循环进行计数并获得平均值。使用trim() aswel 去除空白。
【讨论】:
您可以在这里测试代码: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;
【讨论】: